blob: 661d6ed4af8534dfaae177cdbd8205fa906d3012 [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
Facundo Batista59c58842007-04-10 12:58:45 +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
Raymond Hettingerabe32372008-02-14 02:41:22 +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)
Raymond Hettingerabe32372008-02-14 02:41:22 +000045Decimal('0')
46>>> Decimal('1')
47Decimal('1')
48>>> Decimal('-.0123')
49Decimal('-0.0123')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000050>>> Decimal(123456)
Raymond Hettingerabe32372008-02-14 02:41:22 +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)
59>>> print dig / Decimal(3)
600.333333333
61>>> getcontext().prec = 18
62>>> print dig / Decimal(3)
630.333333333333333333
64>>> print dig.sqrt()
651
66>>> print Decimal(3).sqrt()
671.73205080756887729
68>>> print Decimal(3) ** 123
694.85192780976896427E+58
70>>> inf = Decimal(1) / Decimal(0)
71>>> print inf
72Infinity
73>>> neginf = Decimal(-1) / Decimal(0)
74>>> print neginf
75-Infinity
76>>> print neginf + inf
77NaN
78>>> print neginf * inf
79-Infinity
80>>> print dig / 0
81Infinity
Raymond Hettingerbf440692004-07-10 14:14:37 +000082>>> getcontext().traps[DivisionByZero] = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +000083>>> print dig / 0
84Traceback (most recent call last):
85 ...
86 ...
87 ...
88DivisionByZero: x / 0
89>>> c = Context()
Raymond Hettingerbf440692004-07-10 14:14:37 +000090>>> c.traps[InvalidOperation] = 0
Raymond Hettinger5aa478b2004-07-09 10:02:53 +000091>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000920
93>>> c.divide(Decimal(0), Decimal(0))
Raymond Hettingerabe32372008-02-14 02:41:22 +000094Decimal('NaN')
Raymond Hettingerbf440692004-07-10 14:14:37 +000095>>> c.traps[InvalidOperation] = 1
Raymond Hettinger5aa478b2004-07-09 10:02:53 +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
99>>> print c.flags[InvalidOperation]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001000
101>>> print c.divide(Decimal(0), Decimal(0))
102Traceback (most recent call last):
103 ...
104 ...
105 ...
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000106InvalidOperation: 0 / 0
107>>> 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
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000111>>> print c.divide(Decimal(0), Decimal(0))
112NaN
Raymond Hettinger5aa478b2004-07-09 10:02:53 +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',
Facundo Batista353750c2007-09-13 18:13:15 +0000131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000132
133 # Functions for manipulating contexts
Nick Coghlan8b6999b2006-08-31 12:00:43 +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 Hettinger7c85fa42004-07-01 11:01:35 +0000138
Raymond Hettinger097a1902008-01-11 02:24:13 +0000139try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142except ImportError:
143 DecimalTuple = lambda *args: args
144
Facundo Batista59c58842007-04-10 12:58:45 +0000145# Rounding
Raymond Hettinger0ea241e2004-07-04 13:53:24 +0000146ROUND_DOWN = 'ROUND_DOWN'
147ROUND_HALF_UP = 'ROUND_HALF_UP'
148ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149ROUND_CEILING = 'ROUND_CEILING'
150ROUND_FLOOR = 'ROUND_FLOOR'
151ROUND_UP = 'ROUND_UP'
152ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
Facundo Batista353750c2007-09-13 18:13:15 +0000153ROUND_05UP = 'ROUND_05UP'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000154
Facundo Batista59c58842007-04-10 12:58:45 +0000155# Errors
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000156
157class DecimalException(ArithmeticError):
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000158 """Base exception class.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000159
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
164 anything, though.
165
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
175 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000176 def handle(self, context, *args):
177 pass
178
179
180class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
182
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
Facundo Batista59c58842007-04-10 12:58:45 +0000185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
190 """
191
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000192class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
194
195 Various bad things cause this:
196
197 Something creates a signaling NaN
198 -INF + INF
Facundo Batista59c58842007-04-10 12:58:45 +0000199 0 * (+-)INF
200 (+-)INF / (+-)INF
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
Facundo Batista353750c2007-09-13 18:13:15 +0000209
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000214 """
215 def handle(self, context, *args):
216 if args:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000219 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000220
221class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
223
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
Facundo Batista59c58842007-04-10 12:58:45 +0000226 syntax. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000227 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000228 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000229 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000230
231class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
233
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
238
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
242 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000243
Facundo Batistacce8df22007-09-18 16:53:18 +0000244 def handle(self, context, sign, *args):
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000245 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000246
247class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
249
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
Facundo Batista59c58842007-04-10 12:58:45 +0000252 longer than precision). The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000253 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000254
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000255 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000256 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000257
258class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
260
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
Facundo Batista59c58842007-04-10 12:58:45 +0000263 the dividend is also zero. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000264 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000265
Facundo Batistacce8df22007-09-18 16:53:18 +0000266 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000267 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000268
269class Inexact(DecimalException):
270 """Had to round, losing information.
271
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
Facundo Batista59c58842007-04-10 12:58:45 +0000274 were non-zero), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000275 result in all cases is unchanged.
276
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
279 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000280
281class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
283
284 This occurs and signals invalid-operation if an invalid context was
Facundo Batista59c58842007-04-10 12:58:45 +0000285 detected during an operation. This can occur if contexts are not checked
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
Facundo Batista59c58842007-04-10 12:58:45 +0000288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000290 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000291
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000292 def handle(self, context, *args):
Mark Dickinsonfd6032d2009-01-02 23:16:51 +0000293 return _NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000294
295class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
297
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
Facundo Batista59c58842007-04-10 12:58:45 +0000300 coefficient), or if an overflow or underflow condition occurs. The
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000301 result in all cases is unchanged.
302
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
305 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000306
307class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
309
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
Facundo Batista59c58842007-04-10 12:58:45 +0000312 Emin, before any rounding). The result in all cases is unchanged.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000313
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
316 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000317
318class Overflow(Inexact, Rounded):
319 """Numerical overflow.
320
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
325
326 The result depends on the rounding mode:
327
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
Facundo Batista59c58842007-04-10 12:58:45 +0000330 where sign is the sign of the intermediate result. For round-down, the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000331 result is the largest finite number that can be represented in the
Facundo Batista59c58842007-04-10 12:58:45 +0000332 current precision, with the sign of the intermediate result. For
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000333 round-ceiling, the result is the same as for round-down if the sign of
Facundo Batista59c58842007-04-10 12:58:45 +0000334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000335 the result is the same as for round-down if the sign of the intermediate
Facundo Batista59c58842007-04-10 12:58:45 +0000336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000337 will also be raised.
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000338 """
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000339
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
Facundo Batista353750c2007-09-13 18:13:15 +0000342 ROUND_HALF_DOWN, ROUND_UP):
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000343 return _SignedInfinity[sign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000346 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
Mark Dickinsone4d46b22009-01-03 12:09:22 +0000351 return _SignedInfinity[sign]
Facundo Batista72bc54f2007-11-23 17:59:00 +0000352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000354
355
356class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
358
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
Facundo Batista59c58842007-04-10 12:58:45 +0000362 Emin). That is, the result is both inexact and subnormal.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000363
364 The result after an underflow will be a subnormal number rounded, if
Facundo Batista59c58842007-04-10 12:58:45 +0000365 necessary, so that its exponent is not less than Etiny. This may result
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000366 in 0 with the sign of the intermediate result and an exponent of Etiny.
367
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
369 """
370
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000371# List of public traps and flags
Raymond Hettingerfed52962004-07-14 15:41:57 +0000372_signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000373 Underflow, InvalidOperation, Subnormal]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000374
Raymond Hettinger5aa478b2004-07-09 10:02:53 +0000375# Map conditions (per the spec) to signals
376_condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000380
Facundo Batista59c58842007-04-10 12:58:45 +0000381##### Context Functions ##################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000382
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000383# The getcontext() and setcontext() function manage access to a thread-local
384# current context. Py2.4 offers direct support for thread locals. If that
385# is not available, use threading.currentThread() which is slower but will
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000386# work for older Pythons. If threads are not part of the build, create a
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000387# mock threading object with threading.local() returning the module namespace.
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000388
389try:
390 import threading
391except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
Facundo Batista59c58842007-04-10 12:58:45 +0000394 class MockThreading(object):
Raymond Hettinger7e71fa52004-12-18 19:07:19 +0000395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000399
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000400try:
401 threading.local
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000402
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000403except AttributeError:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000404
Facundo Batista59c58842007-04-10 12:58:45 +0000405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000407 if hasattr(threading.currentThread(), '__decimal_context__'):
408 del threading.currentThread().__decimal_context__
409
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000413 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000414 context.clear_flags()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000415 threading.currentThread().__decimal_context__ = context
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000416
417 def getcontext():
418 """Returns this thread's context.
419
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
423 """
424 try:
425 return threading.currentThread().__decimal_context__
426 except AttributeError:
427 context = Context()
428 threading.currentThread().__decimal_context__ = context
429 return context
430
431else:
432
433 local = threading.local()
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000436
437 def getcontext(_local=local):
438 """Returns this thread's context.
439
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
443 """
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
450
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
Raymond Hettinger9fce44b2004-08-08 04:03:24 +0000454 context = context.copy()
Raymond Hettinger61992ef2004-08-06 23:42:16 +0000455 context.clear_flags()
Raymond Hettingeref66deb2004-07-14 21:04:27 +0000456 _local.__decimal_context__ = context
457
Martin v. Löwiscfe31282006-07-19 17:18:32 +0000458 del threading, local # Don't contaminate the namespace
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000459
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000460def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
462
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
465 in a with statement:
466 def sin(x):
467 with localcontext() as ctx:
468 ctx.prec += 2
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
Facundo Batista59c58842007-04-10 12:58:45 +0000471 return +s # Convert result to normal precision
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000472
473 def sin(x):
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
Facundo Batista59c58842007-04-10 12:58:45 +0000478 return +s # Convert result to normal context
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000479
Facundo Batistaee340e52008-05-02 17:39:00 +0000480 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000481 >>> print getcontext().prec
482 28
483 >>> with localcontext():
484 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000485 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000486 ... print ctx.prec
487 ...
488 30
489 >>> with localcontext(ExtendedContext):
490 ... print getcontext().prec
491 ...
492 9
493 >>> print getcontext().prec
494 28
495 """
Nick Coghlanced12182006-09-02 03:54:17 +0000496 if ctx is None: ctx = getcontext()
497 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000498
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
Facundo Batista59c58842007-04-10 12:58:45 +0000500##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
502class Decimal(object):
503 """Floating point class for decimal arithmetic."""
504
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000505 __slots__ = ('_exp','_int','_sign', '_is_special')
506 # Generally, the value of the Decimal instance is given by
507 # (-1)**_sign * _int * 10**_exp
508 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000510 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000511 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000512 """Create a decimal point instance.
513
514 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000515 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000516 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000517 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000518 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000520 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000522 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525
Facundo Batista72bc54f2007-11-23 17:59:00 +0000526 # Note that the coefficient, self._int, is actually stored as
527 # a string rather than as a tuple of digits. This speeds up
528 # the "digits to integer" and "integer to digits" conversions
529 # that are used in almost every arithmetic operation on
530 # Decimals. This is an internal detail: the as_tuple function
531 # and the Decimal constructor still deal with tuples of
532 # digits.
533
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000534 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535
Facundo Batista0d157a02007-11-30 17:15:25 +0000536 # From a string
537 # REs insist on real strings, so we can too.
538 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000539 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 if m is None:
541 if context is None:
542 context = getcontext()
543 return context._raise_error(ConversionSyntax,
544 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000545
Facundo Batista0d157a02007-11-30 17:15:25 +0000546 if m.group('sign') == "-":
547 self._sign = 1
548 else:
549 self._sign = 0
550 intpart = m.group('int')
551 if intpart is not None:
552 # finite number
553 fracpart = m.group('frac')
554 exp = int(m.group('exp') or '0')
555 if fracpart is not None:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000556 self._int = str((intpart+fracpart).lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000557 self._exp = exp - len(fracpart)
558 else:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000559 self._int = str(intpart.lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000560 self._exp = exp
561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000566 self._int = str(diag.lstrip('0'))
Facundo Batista0d157a02007-11-30 17:15:25 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000585 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000636 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], (int, long)):
640 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000641 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
651 raise TypeError("Cannot convert float to Decimal. " +
652 "First convert the float to a string")
653
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000655
656 def _isnan(self):
657 """Returns whether the number is not actually one.
658
659 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000660 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000661 2 if sNaN
662 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000663 if self._is_special:
664 exp = self._exp
665 if exp == 'n':
666 return 1
667 elif exp == 'N':
668 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 return 0
670
671 def _isinfinity(self):
672 """Returns whether the number is infinite
673
674 0 if finite or not a number
675 1 if +INF
676 -1 if -INF
677 """
678 if self._exp == 'F':
679 if self._sign:
680 return -1
681 return 1
682 return 0
683
Facundo Batista353750c2007-09-13 18:13:15 +0000684 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000685 """Returns whether the number is not actually one.
686
687 if self, other are sNaN, signal
688 if self, other are NaN return nan
689 return 0
690
691 Done before operations.
692 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000694 self_is_nan = self._isnan()
695 if other is None:
696 other_is_nan = False
697 else:
698 other_is_nan = other._isnan()
699
700 if self_is_nan or other_is_nan:
701 if context is None:
702 context = getcontext()
703
704 if self_is_nan == 2:
705 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000706 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000707 if other_is_nan == 2:
708 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000709 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000710 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000711 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712
Facundo Batista353750c2007-09-13 18:13:15 +0000713 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000714 return 0
715
Mark Dickinson2fc92632008-02-06 22:10:50 +0000716 def _compare_check_nans(self, other, context):
717 """Version of _check_nans used for the signaling comparisons
718 compare_signal, __le__, __lt__, __ge__, __gt__.
719
720 Signal InvalidOperation if either self or other is a (quiet
721 or signaling) NaN. Signaling NaNs take precedence over quiet
722 NaNs.
723
724 Return 0 if neither operand is a NaN.
725
726 """
727 if context is None:
728 context = getcontext()
729
730 if self._is_special or other._is_special:
731 if self.is_snan():
732 return context._raise_error(InvalidOperation,
733 'comparison involving sNaN',
734 self)
735 elif other.is_snan():
736 return context._raise_error(InvalidOperation,
737 'comparison involving sNaN',
738 other)
739 elif self.is_qnan():
740 return context._raise_error(InvalidOperation,
741 'comparison involving NaN',
742 self)
743 elif other.is_qnan():
744 return context._raise_error(InvalidOperation,
745 'comparison involving NaN',
746 other)
747 return 0
748
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000750 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751
Facundo Batista1a191df2007-10-02 17:01:24 +0000752 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000754 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755
Mark Dickinson2fc92632008-02-06 22:10:50 +0000756 def _cmp(self, other):
757 """Compare the two non-NaN decimal instances self and other.
758
759 Returns -1 if self < other, 0 if self == other and 1
760 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000762 if self._is_special or other._is_special:
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000763 self_inf = self._isinfinity()
764 other_inf = other._isinfinity()
765 if self_inf == other_inf:
766 return 0
767 elif self_inf < other_inf:
768 return -1
769 else:
770 return 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000771
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000772 # check for zeros; Decimal('0') == Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +0000773 if not self:
774 if not other:
775 return 0
776 else:
777 return -((-1)**other._sign)
778 if not other:
779 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000780
Facundo Batista59c58842007-04-10 12:58:45 +0000781 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000782 if other._sign < self._sign:
783 return -1
784 if self._sign < other._sign:
785 return 1
786
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000787 self_adjusted = self.adjusted()
788 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000789 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000790 self_padded = self._int + '0'*(self._exp - other._exp)
791 other_padded = other._int + '0'*(other._exp - self._exp)
Mark Dickinson8ec69bc2009-01-25 10:47:45 +0000792 if self_padded == other_padded:
793 return 0
794 elif self_padded < other_padded:
795 return -(-1)**self._sign
796 else:
797 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000798 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000799 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000800 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000801 return -((-1)**self._sign)
802
Mark Dickinson2fc92632008-02-06 22:10:50 +0000803 # Note: The Decimal standard doesn't cover rich comparisons for
804 # Decimals. In particular, the specification is silent on the
805 # subject of what should happen for a comparison involving a NaN.
806 # We take the following approach:
807 #
808 # == comparisons involving a NaN always return False
809 # != comparisons involving a NaN always return True
810 # <, >, <= and >= comparisons involving a (quiet or signaling)
811 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000812 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000813 #
814 # This behavior is designed to conform as closely as possible to
815 # that specified by IEEE 754.
816
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000817 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000818 other = _convert_other(other)
819 if other is NotImplemented:
820 return other
821 if self.is_nan() or other.is_nan():
822 return False
823 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000824
825 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000826 other = _convert_other(other)
827 if other is NotImplemented:
828 return other
829 if self.is_nan() or other.is_nan():
830 return True
831 return self._cmp(other) != 0
832
833 def __lt__(self, other, context=None):
834 other = _convert_other(other)
835 if other is NotImplemented:
836 return other
837 ans = self._compare_check_nans(other, context)
838 if ans:
839 return False
840 return self._cmp(other) < 0
841
842 def __le__(self, other, context=None):
843 other = _convert_other(other)
844 if other is NotImplemented:
845 return other
846 ans = self._compare_check_nans(other, context)
847 if ans:
848 return False
849 return self._cmp(other) <= 0
850
851 def __gt__(self, other, context=None):
852 other = _convert_other(other)
853 if other is NotImplemented:
854 return other
855 ans = self._compare_check_nans(other, context)
856 if ans:
857 return False
858 return self._cmp(other) > 0
859
860 def __ge__(self, other, context=None):
861 other = _convert_other(other)
862 if other is NotImplemented:
863 return other
864 ans = self._compare_check_nans(other, context)
865 if ans:
866 return False
867 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000868
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000869 def compare(self, other, context=None):
870 """Compares one to another.
871
872 -1 => a < b
873 0 => a = b
874 1 => a > b
875 NaN => one is NaN
876 Like __cmp__, but returns Decimal instances.
877 """
Facundo Batista353750c2007-09-13 18:13:15 +0000878 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000879
Facundo Batista59c58842007-04-10 12:58:45 +0000880 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000881 if (self._is_special or other and other._is_special):
882 ans = self._check_nans(other, context)
883 if ans:
884 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000885
Mark Dickinson2fc92632008-02-06 22:10:50 +0000886 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000887
888 def __hash__(self):
889 """x.__hash__() <==> hash(x)"""
890 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000891 #
892 # The hash of a nonspecial noninteger Decimal must depend only
893 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000894 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000895 if self._is_special:
896 if self._isnan():
897 raise TypeError('Cannot hash a NaN value.')
898 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000899 if not self:
900 return 0
901 if self._isinteger():
902 op = _WorkRep(self.to_integral_value())
903 # to make computation feasible for Decimals with large
904 # exponent, we use the fact that hash(n) == hash(m) for
905 # any two nonzero integers n and m such that (i) n and m
906 # have the same sign, and (ii) n is congruent to m modulo
907 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
908 # hash((-1)**s*c*pow(10, e, 2**64-1).
909 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000910 # The value of a nonzero nonspecial Decimal instance is
911 # faithfully represented by the triple consisting of its sign,
912 # its adjusted exponent, and its coefficient with trailing
913 # zeros removed.
914 return hash((self._sign,
915 self._exp+len(self._int),
916 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
918 def as_tuple(self):
919 """Represents the number as a triple tuple.
920
921 To show the internals exactly as they are.
922 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000923 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000924
925 def __repr__(self):
926 """Represents the number as an instance of Decimal."""
927 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000928 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000929
Facundo Batista353750c2007-09-13 18:13:15 +0000930 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000931 """Return string representation of the number in scientific notation.
932
933 Captures all of the information in the underlying representation.
934 """
935
Facundo Batista62edb712007-12-03 16:29:52 +0000936 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000937 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000938 if self._exp == 'F':
939 return sign + 'Infinity'
940 elif self._exp == 'n':
941 return sign + 'NaN' + self._int
942 else: # self._exp == 'N'
943 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944
Facundo Batista62edb712007-12-03 16:29:52 +0000945 # number of digits of self._int to left of decimal point
946 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000947
Facundo Batista62edb712007-12-03 16:29:52 +0000948 # dotplace is number of digits of self._int to the left of the
949 # decimal point in the mantissa of the output string (that is,
950 # after adjusting the exponent)
951 if self._exp <= 0 and leftdigits > -6:
952 # no exponent required
953 dotplace = leftdigits
954 elif not eng:
955 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000956 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000957 elif self._int == '0':
958 # engineering notation, zero
959 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000960 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000961 # engineering notation, nonzero
962 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000963
Facundo Batista62edb712007-12-03 16:29:52 +0000964 if dotplace <= 0:
965 intpart = '0'
966 fracpart = '.' + '0'*(-dotplace) + self._int
967 elif dotplace >= len(self._int):
968 intpart = self._int+'0'*(dotplace-len(self._int))
969 fracpart = ''
970 else:
971 intpart = self._int[:dotplace]
972 fracpart = '.' + self._int[dotplace:]
973 if leftdigits == dotplace:
974 exp = ''
975 else:
976 if context is None:
977 context = getcontext()
978 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
979
980 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000981
982 def to_eng_string(self, context=None):
983 """Convert to engineering-type string.
984
985 Engineering notation has an exponent which is a multiple of 3, so there
986 are up to 3 digits left of the decimal place.
987
988 Same rules for when in exponential and when as a value as in __str__.
989 """
Facundo Batista353750c2007-09-13 18:13:15 +0000990 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000991
992 def __neg__(self, context=None):
993 """Returns a copy with the sign switched.
994
995 Rounds, if it has reason.
996 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000997 if self._is_special:
998 ans = self._check_nans(context=context)
999 if ans:
1000 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001001
1002 if not self:
1003 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001004 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001005 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001006 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001007
1008 if context is None:
1009 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001010 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001011
1012 def __pos__(self, context=None):
1013 """Returns a copy, unless it is a sNaN.
1014
1015 Rounds the number (if more then precision digits)
1016 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001017 if self._is_special:
1018 ans = self._check_nans(context=context)
1019 if ans:
1020 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001022 if not self:
1023 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001024 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001025 else:
1026 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001027
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001028 if context is None:
1029 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001030 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001031
Facundo Batistae64acfa2007-12-17 14:18:42 +00001032 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001033 """Returns the absolute value of self.
1034
Facundo Batistae64acfa2007-12-17 14:18:42 +00001035 If the keyword argument 'round' is false, do not round. The
1036 expression self.__abs__(round=False) is equivalent to
1037 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001039 if not round:
1040 return self.copy_abs()
1041
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001042 if self._is_special:
1043 ans = self._check_nans(context=context)
1044 if ans:
1045 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001046
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001047 if self._sign:
1048 ans = self.__neg__(context=context)
1049 else:
1050 ans = self.__pos__(context=context)
1051
1052 return ans
1053
1054 def __add__(self, other, context=None):
1055 """Returns self + other.
1056
1057 -INF + INF (or the reverse) cause InvalidOperation errors.
1058 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001059 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001060 if other is NotImplemented:
1061 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001062
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001063 if context is None:
1064 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001065
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001066 if self._is_special or other._is_special:
1067 ans = self._check_nans(other, context)
1068 if ans:
1069 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001071 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001072 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001073 if self._sign != other._sign and other._isinfinity():
1074 return context._raise_error(InvalidOperation, '-INF + INF')
1075 return Decimal(self)
1076 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001077 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001078
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001079 exp = min(self._exp, other._exp)
1080 negativezero = 0
1081 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001082 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001083 negativezero = 1
1084
1085 if not self and not other:
1086 sign = min(self._sign, other._sign)
1087 if negativezero:
1088 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001089 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001090 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001091 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001092 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001093 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001094 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001095 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096 return ans
1097 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001098 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001099 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001100 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 return ans
1102
1103 op1 = _WorkRep(self)
1104 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001105 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001106
1107 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001108 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001109 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001110 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001111 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001112 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001113 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001114 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001115 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001116 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001117 if op1.sign == 1:
1118 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001119 op1.sign, op2.sign = op2.sign, op1.sign
1120 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001121 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001122 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001123 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001125 op1.sign, op2.sign = (0, 0)
1126 else:
1127 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001128 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001129
Raymond Hettinger17931de2004-10-27 06:21:46 +00001130 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001131 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001132 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001133 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001134
1135 result.exp = op1.exp
1136 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001137 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001138 return ans
1139
1140 __radd__ = __add__
1141
1142 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001143 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001144 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001145 if other is NotImplemented:
1146 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001148 if self._is_special or other._is_special:
1149 ans = self._check_nans(other, context=context)
1150 if ans:
1151 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152
Facundo Batista353750c2007-09-13 18:13:15 +00001153 # self - other is computed as self + other.copy_negate()
1154 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
1156 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001157 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001158 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001159 if other is NotImplemented:
1160 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161
Facundo Batista353750c2007-09-13 18:13:15 +00001162 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001164 def __mul__(self, other, context=None):
1165 """Return self * other.
1166
1167 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1168 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001169 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001170 if other is NotImplemented:
1171 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001172
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001173 if context is None:
1174 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001175
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001176 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001177
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001178 if self._is_special or other._is_special:
1179 ans = self._check_nans(other, context)
1180 if ans:
1181 return ans
1182
1183 if self._isinfinity():
1184 if not other:
1185 return context._raise_error(InvalidOperation, '(+-)INF * 0')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001186 return _SignedInfinity[resultsign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001187
1188 if other._isinfinity():
1189 if not self:
1190 return context._raise_error(InvalidOperation, '0 * (+-)INF')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001191 return _SignedInfinity[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192
1193 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194
1195 # Special case for multiplying by zero
1196 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001197 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001198 # Fixing in case the exponent is out of bounds
1199 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001200 return ans
1201
1202 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001203 if self._int == '1':
1204 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001205 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001207 if other._int == '1':
1208 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001209 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 return ans
1211
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001212 op1 = _WorkRep(self)
1213 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001214
Facundo Batista72bc54f2007-11-23 17:59:00 +00001215 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001216 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
1218 return ans
1219 __rmul__ = __mul__
1220
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001221 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001222 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001224 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001225 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001226
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227 if context is None:
1228 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001229
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001230 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001231
1232 if self._is_special or other._is_special:
1233 ans = self._check_nans(other, context)
1234 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001235 return ans
1236
1237 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001238 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001239
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240 if self._isinfinity():
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001241 return _SignedInfinity[sign]
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001242
1243 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001244 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001245 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001246
1247 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001248 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001249 if not self:
1250 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001251 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001252
Facundo Batistacce8df22007-09-18 16:53:18 +00001253 if not self:
1254 exp = self._exp - other._exp
1255 coeff = 0
1256 else:
1257 # OK, so neither = 0, INF or NaN
1258 shift = len(other._int) - len(self._int) + context.prec + 1
1259 exp = self._exp - other._exp - shift
1260 op1 = _WorkRep(self)
1261 op2 = _WorkRep(other)
1262 if shift >= 0:
1263 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1264 else:
1265 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1266 if remainder:
1267 # result is not exact; adjust to ensure correct rounding
1268 if coeff % 5 == 0:
1269 coeff += 1
1270 else:
1271 # result is exact; get as close to ideal exponent as possible
1272 ideal_exp = self._exp - other._exp
1273 while exp < ideal_exp and coeff % 10 == 0:
1274 coeff //= 10
1275 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Facundo Batista72bc54f2007-11-23 17:59:00 +00001277 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001278 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001279
Facundo Batistacce8df22007-09-18 16:53:18 +00001280 def _divide(self, other, context):
1281 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001282
Facundo Batistacce8df22007-09-18 16:53:18 +00001283 Assumes that neither self nor other is a NaN, that self is not
1284 infinite and that other is nonzero.
1285 """
1286 sign = self._sign ^ other._sign
1287 if other._isinfinity():
1288 ideal_exp = self._exp
1289 else:
1290 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001291
Facundo Batistacce8df22007-09-18 16:53:18 +00001292 expdiff = self.adjusted() - other.adjusted()
1293 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001294 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001295 self._rescale(ideal_exp, context.rounding))
1296 if expdiff <= context.prec:
1297 op1 = _WorkRep(self)
1298 op2 = _WorkRep(other)
1299 if op1.exp >= op2.exp:
1300 op1.int *= 10**(op1.exp - op2.exp)
1301 else:
1302 op2.int *= 10**(op2.exp - op1.exp)
1303 q, r = divmod(op1.int, op2.int)
1304 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001305 return (_dec_from_triple(sign, str(q), 0),
1306 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001307
Facundo Batistacce8df22007-09-18 16:53:18 +00001308 # Here the quotient is too large to be representable
1309 ans = context._raise_error(DivisionImpossible,
1310 'quotient too large in //, % or divmod')
1311 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001313 def __rtruediv__(self, other, context=None):
1314 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001315 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001316 if other is NotImplemented:
1317 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001318 return other.__truediv__(self, context=context)
1319
1320 __div__ = __truediv__
1321 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001322
1323 def __divmod__(self, other, context=None):
1324 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001325 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001326 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001327 other = _convert_other(other)
1328 if other is NotImplemented:
1329 return other
1330
1331 if context is None:
1332 context = getcontext()
1333
1334 ans = self._check_nans(other, context)
1335 if ans:
1336 return (ans, ans)
1337
1338 sign = self._sign ^ other._sign
1339 if self._isinfinity():
1340 if other._isinfinity():
1341 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1342 return ans, ans
1343 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001344 return (_SignedInfinity[sign],
Facundo Batistacce8df22007-09-18 16:53:18 +00001345 context._raise_error(InvalidOperation, 'INF % x'))
1346
1347 if not other:
1348 if not self:
1349 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1350 return ans, ans
1351 else:
1352 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1353 context._raise_error(InvalidOperation, 'x % 0'))
1354
1355 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001356 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001357 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001358
1359 def __rdivmod__(self, other, context=None):
1360 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001361 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001362 if other is NotImplemented:
1363 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364 return other.__divmod__(self, context=context)
1365
1366 def __mod__(self, other, context=None):
1367 """
1368 self % other
1369 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001370 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001371 if other is NotImplemented:
1372 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001373
Facundo Batistacce8df22007-09-18 16:53:18 +00001374 if context is None:
1375 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001376
Facundo Batistacce8df22007-09-18 16:53:18 +00001377 ans = self._check_nans(other, context)
1378 if ans:
1379 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
Facundo Batistacce8df22007-09-18 16:53:18 +00001381 if self._isinfinity():
1382 return context._raise_error(InvalidOperation, 'INF % x')
1383 elif not other:
1384 if self:
1385 return context._raise_error(InvalidOperation, 'x % 0')
1386 else:
1387 return context._raise_error(DivisionUndefined, '0 % 0')
1388
1389 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001390 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001391 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001392
1393 def __rmod__(self, other, context=None):
1394 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001395 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001396 if other is NotImplemented:
1397 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398 return other.__mod__(self, context=context)
1399
1400 def remainder_near(self, other, context=None):
1401 """
1402 Remainder nearest to 0- abs(remainder-near) <= other/2
1403 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001404 if context is None:
1405 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001406
Facundo Batista353750c2007-09-13 18:13:15 +00001407 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001408
Facundo Batista353750c2007-09-13 18:13:15 +00001409 ans = self._check_nans(other, context)
1410 if ans:
1411 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001412
Facundo Batista353750c2007-09-13 18:13:15 +00001413 # self == +/-infinity -> InvalidOperation
1414 if self._isinfinity():
1415 return context._raise_error(InvalidOperation,
1416 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001417
Facundo Batista353750c2007-09-13 18:13:15 +00001418 # other == 0 -> either InvalidOperation or DivisionUndefined
1419 if not other:
1420 if self:
1421 return context._raise_error(InvalidOperation,
1422 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001423 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001424 return context._raise_error(DivisionUndefined,
1425 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001426
Facundo Batista353750c2007-09-13 18:13:15 +00001427 # other = +/-infinity -> remainder = self
1428 if other._isinfinity():
1429 ans = Decimal(self)
1430 return ans._fix(context)
1431
1432 # self = 0 -> remainder = self, with ideal exponent
1433 ideal_exponent = min(self._exp, other._exp)
1434 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001435 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001436 return ans._fix(context)
1437
1438 # catch most cases of large or small quotient
1439 expdiff = self.adjusted() - other.adjusted()
1440 if expdiff >= context.prec + 1:
1441 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001442 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001443 if expdiff <= -2:
1444 # expdiff <= -2 => abs(self/other) < 0.1
1445 ans = self._rescale(ideal_exponent, context.rounding)
1446 return ans._fix(context)
1447
1448 # adjust both arguments to have the same exponent, then divide
1449 op1 = _WorkRep(self)
1450 op2 = _WorkRep(other)
1451 if op1.exp >= op2.exp:
1452 op1.int *= 10**(op1.exp - op2.exp)
1453 else:
1454 op2.int *= 10**(op2.exp - op1.exp)
1455 q, r = divmod(op1.int, op2.int)
1456 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1457 # 10**ideal_exponent. Apply correction to ensure that
1458 # abs(remainder) <= abs(other)/2
1459 if 2*r + (q&1) > op2.int:
1460 r -= op2.int
1461 q += 1
1462
1463 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001464 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001465
1466 # result has same sign as self unless r is negative
1467 sign = self._sign
1468 if r < 0:
1469 sign = 1-sign
1470 r = -r
1471
Facundo Batista72bc54f2007-11-23 17:59:00 +00001472 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001473 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001474
1475 def __floordiv__(self, other, context=None):
1476 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001477 other = _convert_other(other)
1478 if other is NotImplemented:
1479 return other
1480
1481 if context is None:
1482 context = getcontext()
1483
1484 ans = self._check_nans(other, context)
1485 if ans:
1486 return ans
1487
1488 if self._isinfinity():
1489 if other._isinfinity():
1490 return context._raise_error(InvalidOperation, 'INF // INF')
1491 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001492 return _SignedInfinity[self._sign ^ other._sign]
Facundo Batistacce8df22007-09-18 16:53:18 +00001493
1494 if not other:
1495 if self:
1496 return context._raise_error(DivisionByZero, 'x // 0',
1497 self._sign ^ other._sign)
1498 else:
1499 return context._raise_error(DivisionUndefined, '0 // 0')
1500
1501 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001502
1503 def __rfloordiv__(self, other, context=None):
1504 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001505 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001506 if other is NotImplemented:
1507 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001508 return other.__floordiv__(self, context=context)
1509
1510 def __float__(self):
1511 """Float representation."""
1512 return float(str(self))
1513
1514 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001515 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001516 if self._is_special:
1517 if self._isnan():
1518 context = getcontext()
1519 return context._raise_error(InvalidContext)
1520 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001521 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001522 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001523 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001524 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001525 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001526 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001527
Raymond Hettinger5a053642008-01-24 19:05:29 +00001528 __trunc__ = __int__
1529
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001530 def real(self):
1531 return self
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00001532 real = property(real)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001533
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001534 def imag(self):
1535 return Decimal(0)
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00001536 imag = property(imag)
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001537
1538 def conjugate(self):
1539 return self
1540
1541 def __complex__(self):
1542 return complex(float(self))
1543
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001544 def __long__(self):
1545 """Converts to a long.
1546
1547 Equivalent to long(int(self))
1548 """
1549 return long(self.__int__())
1550
Facundo Batista353750c2007-09-13 18:13:15 +00001551 def _fix_nan(self, context):
1552 """Decapitate the payload of a NaN to fit the context"""
1553 payload = self._int
1554
1555 # maximum length of payload is precision if _clamp=0,
1556 # precision-1 if _clamp=1.
1557 max_payload_len = context.prec - context._clamp
1558 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001559 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1560 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001561 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001562
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001563 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001564 """Round if it is necessary to keep self within prec precision.
1565
1566 Rounds and fixes the exponent. Does not raise on a sNaN.
1567
1568 Arguments:
1569 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001570 context - context used.
1571 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001572
Facundo Batista353750c2007-09-13 18:13:15 +00001573 if self._is_special:
1574 if self._isnan():
1575 # decapitate payload if necessary
1576 return self._fix_nan(context)
1577 else:
1578 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001579 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001580
Facundo Batista353750c2007-09-13 18:13:15 +00001581 # if self is zero then exponent should be between Etiny and
1582 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1583 Etiny = context.Etiny()
1584 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001585 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001586 exp_max = [context.Emax, Etop][context._clamp]
1587 new_exp = min(max(self._exp, Etiny), exp_max)
1588 if new_exp != self._exp:
1589 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001590 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001591 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001592 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001593
1594 # exp_min is the smallest allowable exponent of the result,
1595 # equal to max(self.adjusted()-context.prec+1, Etiny)
1596 exp_min = len(self._int) + self._exp - context.prec
1597 if exp_min > Etop:
1598 # overflow: exp_min > Etop iff self.adjusted() > Emax
1599 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001600 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001601 return context._raise_error(Overflow, 'above Emax', self._sign)
1602 self_is_subnormal = exp_min < Etiny
1603 if self_is_subnormal:
1604 context._raise_error(Subnormal)
1605 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001606
Facundo Batista353750c2007-09-13 18:13:15 +00001607 # round if self has too many digits
1608 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001609 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001610 digits = len(self._int) + self._exp - exp_min
1611 if digits < 0:
1612 self = _dec_from_triple(self._sign, '1', exp_min-1)
1613 digits = 0
1614 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1615 changed = this_function(digits)
1616 coeff = self._int[:digits] or '0'
1617 if changed == 1:
1618 coeff = str(int(coeff)+1)
1619 ans = _dec_from_triple(self._sign, coeff, exp_min)
1620
1621 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001622 context._raise_error(Inexact)
1623 if self_is_subnormal:
1624 context._raise_error(Underflow)
1625 if not ans:
1626 # raise Clamped on underflow to 0
1627 context._raise_error(Clamped)
1628 elif len(ans._int) == context.prec+1:
1629 # we get here only if rescaling rounds the
1630 # cofficient up to exactly 10**context.prec
1631 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001632 ans = _dec_from_triple(ans._sign,
1633 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001634 else:
1635 # Inexact and Rounded have already been raised
1636 ans = context._raise_error(Overflow, 'above Emax',
1637 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001638 return ans
1639
Facundo Batista353750c2007-09-13 18:13:15 +00001640 # fold down if _clamp == 1 and self has too few digits
1641 if context._clamp == 1 and self._exp > Etop:
1642 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001643 self_padded = self._int + '0'*(self._exp - Etop)
1644 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001645
Facundo Batista353750c2007-09-13 18:13:15 +00001646 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001647 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001648
1649 _pick_rounding_function = {}
1650
Facundo Batista353750c2007-09-13 18:13:15 +00001651 # for each of the rounding functions below:
1652 # self is a finite, nonzero Decimal
1653 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001654 #
1655 # each function returns either -1, 0, or 1, as follows:
1656 # 1 indicates that self should be rounded up (away from zero)
1657 # 0 indicates that self should be truncated, and that all the
1658 # digits to be truncated are zeros (so the value is unchanged)
1659 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001660
1661 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001662 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001663 if _all_zeros(self._int, prec):
1664 return 0
1665 else:
1666 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001667
Facundo Batista353750c2007-09-13 18:13:15 +00001668 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001669 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001670 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001671
Facundo Batista353750c2007-09-13 18:13:15 +00001672 def _round_half_up(self, prec):
1673 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001674 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001675 return 1
1676 elif _all_zeros(self._int, prec):
1677 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001678 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001679 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001680
1681 def _round_half_down(self, prec):
1682 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001683 if _exact_half(self._int, prec):
1684 return -1
1685 else:
1686 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001687
1688 def _round_half_even(self, prec):
1689 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001690 if _exact_half(self._int, prec) and \
1691 (prec == 0 or self._int[prec-1] in '02468'):
1692 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001693 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001694 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001695
1696 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697 """Rounds up (not away from 0 if negative.)"""
1698 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001699 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001700 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001701 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001702
Facundo Batista353750c2007-09-13 18:13:15 +00001703 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704 """Rounds down (not towards 0 if negative)"""
1705 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001706 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001707 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001708 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001709
Facundo Batista353750c2007-09-13 18:13:15 +00001710 def _round_05up(self, prec):
1711 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001712 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001713 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001714 else:
1715 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001716
Facundo Batista353750c2007-09-13 18:13:15 +00001717 def fma(self, other, third, context=None):
1718 """Fused multiply-add.
1719
1720 Returns self*other+third with no rounding of the intermediate
1721 product self*other.
1722
1723 self and other are multiplied together, with no rounding of
1724 the result. The third operand is then added to the result,
1725 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001726 """
Facundo Batista353750c2007-09-13 18:13:15 +00001727
1728 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001729
1730 # compute product; raise InvalidOperation if either operand is
1731 # a signaling NaN or if the product is zero times infinity.
1732 if self._is_special or other._is_special:
1733 if context is None:
1734 context = getcontext()
1735 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001736 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001737 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001738 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001739 if self._exp == 'n':
1740 product = self
1741 elif other._exp == 'n':
1742 product = other
1743 elif self._exp == 'F':
1744 if not other:
1745 return context._raise_error(InvalidOperation,
1746 'INF * 0 in fma')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001747 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001748 elif other._exp == 'F':
1749 if not self:
1750 return context._raise_error(InvalidOperation,
1751 '0 * INF in fma')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00001752 product = _SignedInfinity[self._sign ^ other._sign]
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001753 else:
1754 product = _dec_from_triple(self._sign ^ other._sign,
1755 str(int(self._int) * int(other._int)),
1756 self._exp + other._exp)
1757
Facundo Batista353750c2007-09-13 18:13:15 +00001758 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001759 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001760
Facundo Batista353750c2007-09-13 18:13:15 +00001761 def _power_modulo(self, other, modulo, context=None):
1762 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001763
Facundo Batista353750c2007-09-13 18:13:15 +00001764 # if can't convert other and modulo to Decimal, raise
1765 # TypeError; there's no point returning NotImplemented (no
1766 # equivalent of __rpow__ for three argument pow)
1767 other = _convert_other(other, raiseit=True)
1768 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001769
Facundo Batista353750c2007-09-13 18:13:15 +00001770 if context is None:
1771 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001772
Facundo Batista353750c2007-09-13 18:13:15 +00001773 # deal with NaNs: if there are any sNaNs then first one wins,
1774 # (i.e. behaviour for NaNs is identical to that of fma)
1775 self_is_nan = self._isnan()
1776 other_is_nan = other._isnan()
1777 modulo_is_nan = modulo._isnan()
1778 if self_is_nan or other_is_nan or modulo_is_nan:
1779 if self_is_nan == 2:
1780 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001781 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001782 if other_is_nan == 2:
1783 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001784 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001785 if modulo_is_nan == 2:
1786 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001787 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001788 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001789 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001790 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001791 return other._fix_nan(context)
1792 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001793
Facundo Batista353750c2007-09-13 18:13:15 +00001794 # check inputs: we apply same restrictions as Python's pow()
1795 if not (self._isinteger() and
1796 other._isinteger() and
1797 modulo._isinteger()):
1798 return context._raise_error(InvalidOperation,
1799 'pow() 3rd argument not allowed '
1800 'unless all arguments are integers')
1801 if other < 0:
1802 return context._raise_error(InvalidOperation,
1803 'pow() 2nd argument cannot be '
1804 'negative when 3rd argument specified')
1805 if not modulo:
1806 return context._raise_error(InvalidOperation,
1807 'pow() 3rd argument cannot be 0')
1808
1809 # additional restriction for decimal: the modulus must be less
1810 # than 10**prec in absolute value
1811 if modulo.adjusted() >= context.prec:
1812 return context._raise_error(InvalidOperation,
1813 'insufficient precision: pow() 3rd '
1814 'argument must not have more than '
1815 'precision digits')
1816
1817 # define 0**0 == NaN, for consistency with two-argument pow
1818 # (even though it hurts!)
1819 if not other and not self:
1820 return context._raise_error(InvalidOperation,
1821 'at least one of pow() 1st argument '
1822 'and 2nd argument must be nonzero ;'
1823 '0**0 is not defined')
1824
1825 # compute sign of result
1826 if other._iseven():
1827 sign = 0
1828 else:
1829 sign = self._sign
1830
1831 # convert modulo to a Python integer, and self and other to
1832 # Decimal integers (i.e. force their exponents to be >= 0)
1833 modulo = abs(int(modulo))
1834 base = _WorkRep(self.to_integral_value())
1835 exponent = _WorkRep(other.to_integral_value())
1836
1837 # compute result using integer pow()
1838 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1839 for i in xrange(exponent.exp):
1840 base = pow(base, 10, modulo)
1841 base = pow(base, exponent.int, modulo)
1842
Facundo Batista72bc54f2007-11-23 17:59:00 +00001843 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001844
1845 def _power_exact(self, other, p):
1846 """Attempt to compute self**other exactly.
1847
1848 Given Decimals self and other and an integer p, attempt to
1849 compute an exact result for the power self**other, with p
1850 digits of precision. Return None if self**other is not
1851 exactly representable in p digits.
1852
1853 Assumes that elimination of special cases has already been
1854 performed: self and other must both be nonspecial; self must
1855 be positive and not numerically equal to 1; other must be
1856 nonzero. For efficiency, other._exp should not be too large,
1857 so that 10**abs(other._exp) is a feasible calculation."""
1858
1859 # In the comments below, we write x for the value of self and
1860 # y for the value of other. Write x = xc*10**xe and y =
1861 # yc*10**ye.
1862
1863 # The main purpose of this method is to identify the *failure*
1864 # of x**y to be exactly representable with as little effort as
1865 # possible. So we look for cheap and easy tests that
1866 # eliminate the possibility of x**y being exact. Only if all
1867 # these tests are passed do we go on to actually compute x**y.
1868
1869 # Here's the main idea. First normalize both x and y. We
1870 # express y as a rational m/n, with m and n relatively prime
1871 # and n>0. Then for x**y to be exactly representable (at
1872 # *any* precision), xc must be the nth power of a positive
1873 # integer and xe must be divisible by n. If m is negative
1874 # then additionally xc must be a power of either 2 or 5, hence
1875 # a power of 2**n or 5**n.
1876 #
1877 # There's a limit to how small |y| can be: if y=m/n as above
1878 # then:
1879 #
1880 # (1) if xc != 1 then for the result to be representable we
1881 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1882 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1883 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1884 # representable.
1885 #
1886 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1887 # |y| < 1/|xe| then the result is not representable.
1888 #
1889 # Note that since x is not equal to 1, at least one of (1) and
1890 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1891 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1892 #
1893 # There's also a limit to how large y can be, at least if it's
1894 # positive: the normalized result will have coefficient xc**y,
1895 # so if it's representable then xc**y < 10**p, and y <
1896 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1897 # not exactly representable.
1898
1899 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1900 # so |y| < 1/xe and the result is not representable.
1901 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1902 # < 1/nbits(xc).
1903
1904 x = _WorkRep(self)
1905 xc, xe = x.int, x.exp
1906 while xc % 10 == 0:
1907 xc //= 10
1908 xe += 1
1909
1910 y = _WorkRep(other)
1911 yc, ye = y.int, y.exp
1912 while yc % 10 == 0:
1913 yc //= 10
1914 ye += 1
1915
1916 # case where xc == 1: result is 10**(xe*y), with xe*y
1917 # required to be an integer
1918 if xc == 1:
1919 if ye >= 0:
1920 exponent = xe*yc*10**ye
1921 else:
1922 exponent, remainder = divmod(xe*yc, 10**-ye)
1923 if remainder:
1924 return None
1925 if y.sign == 1:
1926 exponent = -exponent
1927 # if other is a nonnegative integer, use ideal exponent
1928 if other._isinteger() and other._sign == 0:
1929 ideal_exponent = self._exp*int(other)
1930 zeros = min(exponent-ideal_exponent, p-1)
1931 else:
1932 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001933 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001934
1935 # case where y is negative: xc must be either a power
1936 # of 2 or a power of 5.
1937 if y.sign == 1:
1938 last_digit = xc % 10
1939 if last_digit in (2,4,6,8):
1940 # quick test for power of 2
1941 if xc & -xc != xc:
1942 return None
1943 # now xc is a power of 2; e is its exponent
1944 e = _nbits(xc)-1
1945 # find e*y and xe*y; both must be integers
1946 if ye >= 0:
1947 y_as_int = yc*10**ye
1948 e = e*y_as_int
1949 xe = xe*y_as_int
1950 else:
1951 ten_pow = 10**-ye
1952 e, remainder = divmod(e*yc, ten_pow)
1953 if remainder:
1954 return None
1955 xe, remainder = divmod(xe*yc, ten_pow)
1956 if remainder:
1957 return None
1958
1959 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1960 return None
1961 xc = 5**e
1962
1963 elif last_digit == 5:
1964 # e >= log_5(xc) if xc is a power of 5; we have
1965 # equality all the way up to xc=5**2658
1966 e = _nbits(xc)*28//65
1967 xc, remainder = divmod(5**e, xc)
1968 if remainder:
1969 return None
1970 while xc % 5 == 0:
1971 xc //= 5
1972 e -= 1
1973 if ye >= 0:
1974 y_as_integer = yc*10**ye
1975 e = e*y_as_integer
1976 xe = xe*y_as_integer
1977 else:
1978 ten_pow = 10**-ye
1979 e, remainder = divmod(e*yc, ten_pow)
1980 if remainder:
1981 return None
1982 xe, remainder = divmod(xe*yc, ten_pow)
1983 if remainder:
1984 return None
1985 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1986 return None
1987 xc = 2**e
1988 else:
1989 return None
1990
1991 if xc >= 10**p:
1992 return None
1993 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001994 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001995
1996 # now y is positive; find m and n such that y = m/n
1997 if ye >= 0:
1998 m, n = yc*10**ye, 1
1999 else:
2000 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2001 return None
2002 xc_bits = _nbits(xc)
2003 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2004 return None
2005 m, n = yc, 10**(-ye)
2006 while m % 2 == n % 2 == 0:
2007 m //= 2
2008 n //= 2
2009 while m % 5 == n % 5 == 0:
2010 m //= 5
2011 n //= 5
2012
2013 # compute nth root of xc*10**xe
2014 if n > 1:
2015 # if 1 < xc < 2**n then xc isn't an nth power
2016 if xc != 1 and xc_bits <= n:
2017 return None
2018
2019 xe, rem = divmod(xe, n)
2020 if rem != 0:
2021 return None
2022
2023 # compute nth root of xc using Newton's method
2024 a = 1L << -(-_nbits(xc)//n) # initial estimate
2025 while True:
2026 q, r = divmod(xc, a**(n-1))
2027 if a <= q:
2028 break
2029 else:
2030 a = (a*(n-1) + q)//n
2031 if not (a == q and r == 0):
2032 return None
2033 xc = a
2034
2035 # now xc*10**xe is the nth root of the original xc*10**xe
2036 # compute mth power of xc*10**xe
2037
2038 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2039 # 10**p and the result is not representable.
2040 if xc > 1 and m > p*100//_log10_lb(xc):
2041 return None
2042 xc = xc**m
2043 xe *= m
2044 if xc > 10**p:
2045 return None
2046
2047 # by this point the result *is* exactly representable
2048 # adjust the exponent to get as close as possible to the ideal
2049 # exponent, if necessary
2050 str_xc = str(xc)
2051 if other._isinteger() and other._sign == 0:
2052 ideal_exponent = self._exp*int(other)
2053 zeros = min(xe-ideal_exponent, p-len(str_xc))
2054 else:
2055 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002056 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002057
2058 def __pow__(self, other, modulo=None, context=None):
2059 """Return self ** other [ % modulo].
2060
2061 With two arguments, compute self**other.
2062
2063 With three arguments, compute (self**other) % modulo. For the
2064 three argument form, the following restrictions on the
2065 arguments hold:
2066
2067 - all three arguments must be integral
2068 - other must be nonnegative
2069 - either self or other (or both) must be nonzero
2070 - modulo must be nonzero and must have at most p digits,
2071 where p is the context precision.
2072
2073 If any of these restrictions is violated the InvalidOperation
2074 flag is raised.
2075
2076 The result of pow(self, other, modulo) is identical to the
2077 result that would be obtained by computing (self**other) %
2078 modulo with unbounded precision, but is computed more
2079 efficiently. It is always exact.
2080 """
2081
2082 if modulo is not None:
2083 return self._power_modulo(other, modulo, context)
2084
2085 other = _convert_other(other)
2086 if other is NotImplemented:
2087 return other
2088
2089 if context is None:
2090 context = getcontext()
2091
2092 # either argument is a NaN => result is NaN
2093 ans = self._check_nans(other, context)
2094 if ans:
2095 return ans
2096
2097 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2098 if not other:
2099 if not self:
2100 return context._raise_error(InvalidOperation, '0 ** 0')
2101 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002102 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002103
2104 # result has sign 1 iff self._sign is 1 and other is an odd integer
2105 result_sign = 0
2106 if self._sign == 1:
2107 if other._isinteger():
2108 if not other._iseven():
2109 result_sign = 1
2110 else:
2111 # -ve**noninteger = NaN
2112 # (-0)**noninteger = 0**noninteger
2113 if self:
2114 return context._raise_error(InvalidOperation,
2115 'x ** y with x negative and y not an integer')
2116 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002117 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002118
2119 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2120 if not self:
2121 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002122 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002123 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002124 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002125
2126 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002127 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002128 if other._sign == 0:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002129 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002130 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002131 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002132
Facundo Batista353750c2007-09-13 18:13:15 +00002133 # 1**other = 1, but the choice of exponent and the flags
2134 # depend on the exponent of self, and on whether other is a
2135 # positive integer, a negative integer, or neither
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002136 if self == _One:
Facundo Batista353750c2007-09-13 18:13:15 +00002137 if other._isinteger():
2138 # exp = max(self._exp*max(int(other), 0),
2139 # 1-context.prec) but evaluating int(other) directly
2140 # is dangerous until we know other is small (other
2141 # could be 1e999999999)
2142 if other._sign == 1:
2143 multiplier = 0
2144 elif other > context.prec:
2145 multiplier = context.prec
2146 else:
2147 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002148
Facundo Batista353750c2007-09-13 18:13:15 +00002149 exp = self._exp * multiplier
2150 if exp < 1-context.prec:
2151 exp = 1-context.prec
2152 context._raise_error(Rounded)
2153 else:
2154 context._raise_error(Inexact)
2155 context._raise_error(Rounded)
2156 exp = 1-context.prec
2157
Facundo Batista72bc54f2007-11-23 17:59:00 +00002158 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002159
2160 # compute adjusted exponent of self
2161 self_adj = self.adjusted()
2162
2163 # self ** infinity is infinity if self > 1, 0 if self < 1
2164 # self ** -infinity is infinity if self < 1, 0 if self > 1
2165 if other._isinfinity():
2166 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002167 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002168 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002169 return _SignedInfinity[result_sign]
Facundo Batista353750c2007-09-13 18:13:15 +00002170
2171 # from here on, the result always goes through the call
2172 # to _fix at the end of this function.
2173 ans = None
2174
2175 # crude test to catch cases of extreme overflow/underflow. If
2176 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2177 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2178 # self**other >= 10**(Emax+1), so overflow occurs. The test
2179 # for underflow is similar.
2180 bound = self._log10_exp_bound() + other.adjusted()
2181 if (self_adj >= 0) == (other._sign == 0):
2182 # self > 1 and other +ve, or self < 1 and other -ve
2183 # possibility of overflow
2184 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002185 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002186 else:
2187 # self > 1 and other -ve, or self < 1 and other +ve
2188 # possibility of underflow to 0
2189 Etiny = context.Etiny()
2190 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002191 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002192
2193 # try for an exact result with precision +1
2194 if ans is None:
2195 ans = self._power_exact(other, context.prec + 1)
2196 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002197 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002198
2199 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2200 if ans is None:
2201 p = context.prec
2202 x = _WorkRep(self)
2203 xc, xe = x.int, x.exp
2204 y = _WorkRep(other)
2205 yc, ye = y.int, y.exp
2206 if y.sign == 1:
2207 yc = -yc
2208
2209 # compute correctly rounded result: start with precision +3,
2210 # then increase precision until result is unambiguously roundable
2211 extra = 3
2212 while True:
2213 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2214 if coeff % (5*10**(len(str(coeff))-p-1)):
2215 break
2216 extra += 3
2217
Facundo Batista72bc54f2007-11-23 17:59:00 +00002218 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002219
2220 # the specification says that for non-integer other we need to
2221 # raise Inexact, even when the result is actually exact. In
2222 # the same way, we need to raise Underflow here if the result
2223 # is subnormal. (The call to _fix will take care of raising
2224 # Rounded and Subnormal, as usual.)
2225 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002226 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002227 # pad with zeros up to length context.prec+1 if necessary
2228 if len(ans._int) <= context.prec:
2229 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002230 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2231 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002232 if ans.adjusted() < context.Emin:
2233 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002234
Facundo Batista353750c2007-09-13 18:13:15 +00002235 # unlike exp, ln and log10, the power function respects the
2236 # rounding mode; no need to use ROUND_HALF_EVEN here
2237 ans = ans._fix(context)
2238 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002239
2240 def __rpow__(self, other, context=None):
2241 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002242 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002243 if other is NotImplemented:
2244 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002245 return other.__pow__(self, context=context)
2246
2247 def normalize(self, context=None):
2248 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Facundo Batista353750c2007-09-13 18:13:15 +00002250 if context is None:
2251 context = getcontext()
2252
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002253 if self._is_special:
2254 ans = self._check_nans(context=context)
2255 if ans:
2256 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002258 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259 if dup._isinfinity():
2260 return dup
2261
2262 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002263 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002264 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 end = len(dup._int)
2266 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002267 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002268 exp += 1
2269 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002270 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002271
Facundo Batistabd2fe832007-09-13 18:42:09 +00002272 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002273 """Quantize self so its exponent is the same as that of exp.
2274
2275 Similar to self._rescale(exp._exp) but with error checking.
2276 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002277 exp = _convert_other(exp, raiseit=True)
2278
Facundo Batista353750c2007-09-13 18:13:15 +00002279 if context is None:
2280 context = getcontext()
2281 if rounding is None:
2282 rounding = context.rounding
2283
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 if self._is_special or exp._is_special:
2285 ans = self._check_nans(exp, context)
2286 if ans:
2287 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002288
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002289 if exp._isinfinity() or self._isinfinity():
2290 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002291 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002292 return context._raise_error(InvalidOperation,
2293 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002294
Facundo Batistabd2fe832007-09-13 18:42:09 +00002295 # if we're not watching exponents, do a simple rescale
2296 if not watchexp:
2297 ans = self._rescale(exp._exp, rounding)
2298 # raise Inexact and Rounded where appropriate
2299 if ans._exp > self._exp:
2300 context._raise_error(Rounded)
2301 if ans != self:
2302 context._raise_error(Inexact)
2303 return ans
2304
Facundo Batista353750c2007-09-13 18:13:15 +00002305 # exp._exp should be between Etiny and Emax
2306 if not (context.Etiny() <= exp._exp <= context.Emax):
2307 return context._raise_error(InvalidOperation,
2308 'target exponent out of bounds in quantize')
2309
2310 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002311 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002312 return ans._fix(context)
2313
2314 self_adjusted = self.adjusted()
2315 if self_adjusted > context.Emax:
2316 return context._raise_error(InvalidOperation,
2317 'exponent of quantize result too large for current context')
2318 if self_adjusted - exp._exp + 1 > context.prec:
2319 return context._raise_error(InvalidOperation,
2320 'quantize result has too many digits for current context')
2321
2322 ans = self._rescale(exp._exp, rounding)
2323 if ans.adjusted() > context.Emax:
2324 return context._raise_error(InvalidOperation,
2325 'exponent of quantize result too large for current context')
2326 if len(ans._int) > context.prec:
2327 return context._raise_error(InvalidOperation,
2328 'quantize result has too many digits for current context')
2329
2330 # raise appropriate flags
2331 if ans._exp > self._exp:
2332 context._raise_error(Rounded)
2333 if ans != self:
2334 context._raise_error(Inexact)
2335 if ans and ans.adjusted() < context.Emin:
2336 context._raise_error(Subnormal)
2337
2338 # call to fix takes care of any necessary folddown
2339 ans = ans._fix(context)
2340 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002341
2342 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002343 """Return True if self and other have the same exponent; otherwise
2344 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002345
Facundo Batista1a191df2007-10-02 17:01:24 +00002346 If either operand is a special value, the following rules are used:
2347 * return True if both operands are infinities
2348 * return True if both operands are NaNs
2349 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002350 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002351 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002352 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002353 return (self.is_nan() and other.is_nan() or
2354 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355 return self._exp == other._exp
2356
Facundo Batista353750c2007-09-13 18:13:15 +00002357 def _rescale(self, exp, rounding):
2358 """Rescale self so that the exponent is exp, either by padding with zeros
2359 or by truncating digits, using the given rounding mode.
2360
2361 Specials are returned without change. This operation is
2362 quiet: it raises no flags, and uses no information from the
2363 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364
2365 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002366 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002367 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002368 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002369 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002370 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002371 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002372
Facundo Batista353750c2007-09-13 18:13:15 +00002373 if self._exp >= exp:
2374 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002375 return _dec_from_triple(self._sign,
2376 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002377
Facundo Batista353750c2007-09-13 18:13:15 +00002378 # too many digits; round and lose data. If self.adjusted() <
2379 # exp-1, replace self by 10**(exp-1) before rounding
2380 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002381 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002382 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002383 digits = 0
2384 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002385 changed = this_function(digits)
2386 coeff = self._int[:digits] or '0'
2387 if changed == 1:
2388 coeff = str(int(coeff)+1)
2389 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002390
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002391 def _round(self, places, rounding):
2392 """Round a nonzero, nonspecial Decimal to a fixed number of
2393 significant figures, using the given rounding mode.
2394
2395 Infinities, NaNs and zeros are returned unaltered.
2396
2397 This operation is quiet: it raises no flags, and uses no
2398 information from the context.
2399
2400 """
2401 if places <= 0:
2402 raise ValueError("argument should be at least 1 in _round")
2403 if self._is_special or not self:
2404 return Decimal(self)
2405 ans = self._rescale(self.adjusted()+1-places, rounding)
2406 # it can happen that the rescale alters the adjusted exponent;
2407 # for example when rounding 99.97 to 3 significant figures.
2408 # When this happens we end up with an extra 0 at the end of
2409 # the number; a second rescale fixes this.
2410 if ans.adjusted() != self.adjusted():
2411 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2412 return ans
2413
Facundo Batista353750c2007-09-13 18:13:15 +00002414 def to_integral_exact(self, rounding=None, context=None):
2415 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002416
Facundo Batista353750c2007-09-13 18:13:15 +00002417 If no rounding mode is specified, take the rounding mode from
2418 the context. This method raises the Rounded and Inexact flags
2419 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002420
Facundo Batista353750c2007-09-13 18:13:15 +00002421 See also: to_integral_value, which does exactly the same as
2422 this method except that it doesn't raise Inexact or Rounded.
2423 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002424 if self._is_special:
2425 ans = self._check_nans(context=context)
2426 if ans:
2427 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002428 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002430 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002431 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002432 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002433 if context is None:
2434 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002435 if rounding is None:
2436 rounding = context.rounding
2437 context._raise_error(Rounded)
2438 ans = self._rescale(0, rounding)
2439 if ans != self:
2440 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002441 return ans
2442
Facundo Batista353750c2007-09-13 18:13:15 +00002443 def to_integral_value(self, rounding=None, context=None):
2444 """Rounds to the nearest integer, without raising inexact, rounded."""
2445 if context is None:
2446 context = getcontext()
2447 if rounding is None:
2448 rounding = context.rounding
2449 if self._is_special:
2450 ans = self._check_nans(context=context)
2451 if ans:
2452 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002453 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002454 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002455 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002456 else:
2457 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002458
Facundo Batista353750c2007-09-13 18:13:15 +00002459 # the method name changed, but we provide also the old one, for compatibility
2460 to_integral = to_integral_value
2461
2462 def sqrt(self, context=None):
2463 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002464 if context is None:
2465 context = getcontext()
2466
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002467 if self._is_special:
2468 ans = self._check_nans(context=context)
2469 if ans:
2470 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002471
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002472 if self._isinfinity() and self._sign == 0:
2473 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002474
2475 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002476 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002477 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002478 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002479
2480 if self._sign == 1:
2481 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2482
Facundo Batista353750c2007-09-13 18:13:15 +00002483 # At this point self represents a positive number. Let p be
2484 # the desired precision and express self in the form c*100**e
2485 # with c a positive real number and e an integer, c and e
2486 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2487 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2488 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2489 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2490 # the closest integer to sqrt(c) with the even integer chosen
2491 # in the case of a tie.
2492 #
2493 # To ensure correct rounding in all cases, we use the
2494 # following trick: we compute the square root to an extra
2495 # place (precision p+1 instead of precision p), rounding down.
2496 # Then, if the result is inexact and its last digit is 0 or 5,
2497 # we increase the last digit to 1 or 6 respectively; if it's
2498 # exact we leave the last digit alone. Now the final round to
2499 # p places (or fewer in the case of underflow) will round
2500 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002501
Facundo Batista353750c2007-09-13 18:13:15 +00002502 # use an extra digit of precision
2503 prec = context.prec+1
2504
2505 # write argument in the form c*100**e where e = self._exp//2
2506 # is the 'ideal' exponent, to be used if the square root is
2507 # exactly representable. l is the number of 'digits' of c in
2508 # base 100, so that 100**(l-1) <= c < 100**l.
2509 op = _WorkRep(self)
2510 e = op.exp >> 1
2511 if op.exp & 1:
2512 c = op.int * 10
2513 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002514 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002515 c = op.int
2516 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002517
Facundo Batista353750c2007-09-13 18:13:15 +00002518 # rescale so that c has exactly prec base 100 'digits'
2519 shift = prec-l
2520 if shift >= 0:
2521 c *= 100**shift
2522 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002523 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002524 c, remainder = divmod(c, 100**-shift)
2525 exact = not remainder
2526 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002527
Facundo Batista353750c2007-09-13 18:13:15 +00002528 # find n = floor(sqrt(c)) using Newton's method
2529 n = 10**prec
2530 while True:
2531 q = c//n
2532 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002533 break
Facundo Batista353750c2007-09-13 18:13:15 +00002534 else:
2535 n = n + q >> 1
2536 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002537
Facundo Batista353750c2007-09-13 18:13:15 +00002538 if exact:
2539 # result is exact; rescale to use ideal exponent e
2540 if shift >= 0:
2541 # assert n % 10**shift == 0
2542 n //= 10**shift
2543 else:
2544 n *= 10**-shift
2545 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002547 # result is not exact; fix last digit as described above
2548 if n % 5 == 0:
2549 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550
Facundo Batista72bc54f2007-11-23 17:59:00 +00002551 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552
Facundo Batista353750c2007-09-13 18:13:15 +00002553 # round, and fit to current context
2554 context = context._shallow_copy()
2555 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002556 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002557 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002558
Facundo Batista353750c2007-09-13 18:13:15 +00002559 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
2561 def max(self, other, context=None):
2562 """Returns the larger value.
2563
Facundo Batista353750c2007-09-13 18:13:15 +00002564 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002565 NaN (and signals if one is sNaN). Also rounds.
2566 """
Facundo Batista353750c2007-09-13 18:13:15 +00002567 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002568
Facundo Batista6c398da2007-09-17 17:30:13 +00002569 if context is None:
2570 context = getcontext()
2571
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002572 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002573 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002574 # number is always returned
2575 sn = self._isnan()
2576 on = other._isnan()
2577 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00002578 if on == 1 and sn == 0:
2579 return self._fix(context)
2580 if sn == 1 and on == 0:
2581 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002582 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002583
Mark Dickinson2fc92632008-02-06 22:10:50 +00002584 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002585 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002586 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002587 # then an ordering is applied:
2588 #
Facundo Batista59c58842007-04-10 12:58:45 +00002589 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002590 # positive sign and min returns the operand with the negative sign
2591 #
Facundo Batista59c58842007-04-10 12:58:45 +00002592 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002593 # the result. This is exactly the ordering used in compare_total.
2594 c = self.compare_total(other)
2595
2596 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002597 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002598 else:
2599 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002600
Facundo Batistae64acfa2007-12-17 14:18:42 +00002601 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
2603 def min(self, other, context=None):
2604 """Returns the smaller value.
2605
Facundo Batista59c58842007-04-10 12:58:45 +00002606 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002607 NaN (and signals if one is sNaN). Also rounds.
2608 """
Facundo Batista353750c2007-09-13 18:13:15 +00002609 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002610
Facundo Batista6c398da2007-09-17 17:30:13 +00002611 if context is None:
2612 context = getcontext()
2613
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002614 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002615 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002616 # number is always returned
2617 sn = self._isnan()
2618 on = other._isnan()
2619 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00002620 if on == 1 and sn == 0:
2621 return self._fix(context)
2622 if sn == 1 and on == 0:
2623 return other._fix(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002624 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625
Mark Dickinson2fc92632008-02-06 22:10:50 +00002626 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002627 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002628 c = self.compare_total(other)
2629
2630 if c == -1:
2631 ans = self
2632 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002634
Facundo Batistae64acfa2007-12-17 14:18:42 +00002635 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002636
2637 def _isinteger(self):
2638 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002639 if self._is_special:
2640 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002641 if self._exp >= 0:
2642 return True
2643 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002644 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002645
2646 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002647 """Returns True if self is even. Assumes self is an integer."""
2648 if not self or self._exp > 0:
2649 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002650 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002651
2652 def adjusted(self):
2653 """Return the adjusted exponent of self"""
2654 try:
2655 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002656 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002657 except TypeError:
2658 return 0
2659
Facundo Batista353750c2007-09-13 18:13:15 +00002660 def canonical(self, context=None):
2661 """Returns the same Decimal object.
2662
2663 As we do not have different encodings for the same number, the
2664 received object already is in its canonical form.
2665 """
2666 return self
2667
2668 def compare_signal(self, other, context=None):
2669 """Compares self to the other operand numerically.
2670
2671 It's pretty much like compare(), but all NaNs signal, with signaling
2672 NaNs taking precedence over quiet NaNs.
2673 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002674 other = _convert_other(other, raiseit = True)
2675 ans = self._compare_check_nans(other, context)
2676 if ans:
2677 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002678 return self.compare(other, context=context)
2679
2680 def compare_total(self, other):
2681 """Compares self to other using the abstract representations.
2682
2683 This is not like the standard compare, which use their numerical
2684 value. Note that a total ordering is defined for all possible abstract
2685 representations.
2686 """
2687 # if one is negative and the other is positive, it's easy
2688 if self._sign and not other._sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002689 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002690 if not self._sign and other._sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002691 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002692 sign = self._sign
2693
2694 # let's handle both NaN types
2695 self_nan = self._isnan()
2696 other_nan = other._isnan()
2697 if self_nan or other_nan:
2698 if self_nan == other_nan:
2699 if self._int < other._int:
2700 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002701 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002702 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002703 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002704 if self._int > other._int:
2705 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002706 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002707 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002708 return _One
2709 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002710
2711 if sign:
2712 if self_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002713 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002714 if other_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002715 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002716 if self_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002717 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002718 if other_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002719 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002720 else:
2721 if self_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002722 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002723 if other_nan == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002724 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002725 if self_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002726 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002727 if other_nan == 2:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002728 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002729
2730 if self < other:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002731 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002732 if self > other:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002733 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002734
2735 if self._exp < other._exp:
2736 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002737 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002738 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002739 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002740 if self._exp > other._exp:
2741 if sign:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002742 return _NegativeOne
Facundo Batista353750c2007-09-13 18:13:15 +00002743 else:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002744 return _One
2745 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002746
2747
2748 def compare_total_mag(self, other):
2749 """Compares self to other using abstract repr., ignoring sign.
2750
2751 Like compare_total, but with operand's sign ignored and assumed to be 0.
2752 """
2753 s = self.copy_abs()
2754 o = other.copy_abs()
2755 return s.compare_total(o)
2756
2757 def copy_abs(self):
2758 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002759 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002760
2761 def copy_negate(self):
2762 """Returns a copy with the sign inverted."""
2763 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002764 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002765 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002766 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002767
2768 def copy_sign(self, other):
2769 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002770 return _dec_from_triple(other._sign, self._int,
2771 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002772
2773 def exp(self, context=None):
2774 """Returns e ** self."""
2775
2776 if context is None:
2777 context = getcontext()
2778
2779 # exp(NaN) = NaN
2780 ans = self._check_nans(context=context)
2781 if ans:
2782 return ans
2783
2784 # exp(-Infinity) = 0
2785 if self._isinfinity() == -1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002786 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002787
2788 # exp(0) = 1
2789 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002790 return _One
Facundo Batista353750c2007-09-13 18:13:15 +00002791
2792 # exp(Infinity) = Infinity
2793 if self._isinfinity() == 1:
2794 return Decimal(self)
2795
2796 # the result is now guaranteed to be inexact (the true
2797 # mathematical result is transcendental). There's no need to
2798 # raise Rounded and Inexact here---they'll always be raised as
2799 # a result of the call to _fix.
2800 p = context.prec
2801 adj = self.adjusted()
2802
2803 # we only need to do any computation for quite a small range
2804 # of adjusted exponents---for example, -29 <= adj <= 10 for
2805 # the default context. For smaller exponent the result is
2806 # indistinguishable from 1 at the given precision, while for
2807 # larger exponent the result either overflows or underflows.
2808 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2809 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002810 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002811 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2812 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002813 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002814 elif self._sign == 0 and adj < -p:
2815 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002816 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002817 elif self._sign == 1 and adj < -p-1:
2818 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002819 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002820 # general case
2821 else:
2822 op = _WorkRep(self)
2823 c, e = op.int, op.exp
2824 if op.sign == 1:
2825 c = -c
2826
2827 # compute correctly rounded result: increase precision by
2828 # 3 digits at a time until we get an unambiguously
2829 # roundable result
2830 extra = 3
2831 while True:
2832 coeff, exp = _dexp(c, e, p+extra)
2833 if coeff % (5*10**(len(str(coeff))-p-1)):
2834 break
2835 extra += 3
2836
Facundo Batista72bc54f2007-11-23 17:59:00 +00002837 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002838
2839 # at this stage, ans should round correctly with *any*
2840 # rounding mode, not just with ROUND_HALF_EVEN
2841 context = context._shallow_copy()
2842 rounding = context._set_rounding(ROUND_HALF_EVEN)
2843 ans = ans._fix(context)
2844 context.rounding = rounding
2845
2846 return ans
2847
2848 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002849 """Return True if self is canonical; otherwise return False.
2850
2851 Currently, the encoding of a Decimal instance is always
2852 canonical, so this method returns True for any Decimal.
2853 """
2854 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002855
2856 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002857 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002858
Facundo Batista1a191df2007-10-02 17:01:24 +00002859 A Decimal instance is considered finite if it is neither
2860 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002861 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002862 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002863
2864 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002865 """Return True if self is infinite; otherwise return False."""
2866 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002867
2868 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002869 """Return True if self is a qNaN or sNaN; otherwise return False."""
2870 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002871
2872 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002873 """Return True if self is a normal number; otherwise return False."""
2874 if self._is_special or not self:
2875 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002876 if context is None:
2877 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002878 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002879
2880 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002881 """Return True if self is a quiet NaN; otherwise return False."""
2882 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002883
2884 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002885 """Return True if self is negative; otherwise return False."""
2886 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002887
2888 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002889 """Return True if self is a signaling NaN; otherwise return False."""
2890 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002891
2892 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002893 """Return True if self is subnormal; otherwise return False."""
2894 if self._is_special or not self:
2895 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002896 if context is None:
2897 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002898 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002899
2900 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002901 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002902 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002903
2904 def _ln_exp_bound(self):
2905 """Compute a lower bound for the adjusted exponent of self.ln().
2906 In other words, compute r such that self.ln() >= 10**r. Assumes
2907 that self is finite and positive and that self != 1.
2908 """
2909
2910 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2911 adj = self._exp + len(self._int) - 1
2912 if adj >= 1:
2913 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2914 return len(str(adj*23//10)) - 1
2915 if adj <= -2:
2916 # argument <= 0.1
2917 return len(str((-1-adj)*23//10)) - 1
2918 op = _WorkRep(self)
2919 c, e = op.int, op.exp
2920 if adj == 0:
2921 # 1 < self < 10
2922 num = str(c-10**-e)
2923 den = str(c)
2924 return len(num) - len(den) - (num < den)
2925 # adj == -1, 0.1 <= self < 1
2926 return e + len(str(10**-e - c)) - 1
2927
2928
2929 def ln(self, context=None):
2930 """Returns the natural (base e) logarithm of self."""
2931
2932 if context is None:
2933 context = getcontext()
2934
2935 # ln(NaN) = NaN
2936 ans = self._check_nans(context=context)
2937 if ans:
2938 return ans
2939
2940 # ln(0.0) == -Infinity
2941 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002942 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00002943
2944 # ln(Infinity) = Infinity
2945 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002946 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00002947
2948 # ln(1.0) == 0.0
Mark Dickinsone4d46b22009-01-03 12:09:22 +00002949 if self == _One:
2950 return _Zero
Facundo Batista353750c2007-09-13 18:13:15 +00002951
2952 # ln(negative) raises InvalidOperation
2953 if self._sign == 1:
2954 return context._raise_error(InvalidOperation,
2955 'ln of a negative value')
2956
2957 # result is irrational, so necessarily inexact
2958 op = _WorkRep(self)
2959 c, e = op.int, op.exp
2960 p = context.prec
2961
2962 # correctly rounded result: repeatedly increase precision by 3
2963 # until we get an unambiguously roundable result
2964 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2965 while True:
2966 coeff = _dlog(c, e, places)
2967 # assert len(str(abs(coeff)))-p >= 1
2968 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2969 break
2970 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002971 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002972
2973 context = context._shallow_copy()
2974 rounding = context._set_rounding(ROUND_HALF_EVEN)
2975 ans = ans._fix(context)
2976 context.rounding = rounding
2977 return ans
2978
2979 def _log10_exp_bound(self):
2980 """Compute a lower bound for the adjusted exponent of self.log10().
2981 In other words, find r such that self.log10() >= 10**r.
2982 Assumes that self is finite and positive and that self != 1.
2983 """
2984
2985 # For x >= 10 or x < 0.1 we only need a bound on the integer
2986 # part of log10(self), and this comes directly from the
2987 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2988 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2989 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2990
2991 adj = self._exp + len(self._int) - 1
2992 if adj >= 1:
2993 # self >= 10
2994 return len(str(adj))-1
2995 if adj <= -2:
2996 # self < 0.1
2997 return len(str(-1-adj))-1
2998 op = _WorkRep(self)
2999 c, e = op.int, op.exp
3000 if adj == 0:
3001 # 1 < self < 10
3002 num = str(c-10**-e)
3003 den = str(231*c)
3004 return len(num) - len(den) - (num < den) + 2
3005 # adj == -1, 0.1 <= self < 1
3006 num = str(10**-e-c)
3007 return len(num) + e - (num < "231") - 1
3008
3009 def log10(self, context=None):
3010 """Returns the base 10 logarithm of self."""
3011
3012 if context is None:
3013 context = getcontext()
3014
3015 # log10(NaN) = NaN
3016 ans = self._check_nans(context=context)
3017 if ans:
3018 return ans
3019
3020 # log10(0.0) == -Infinity
3021 if not self:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003022 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003023
3024 # log10(Infinity) = Infinity
3025 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003026 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003027
3028 # log10(negative or -Infinity) raises InvalidOperation
3029 if self._sign == 1:
3030 return context._raise_error(InvalidOperation,
3031 'log10 of a negative value')
3032
3033 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003034 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003035 # answer may need rounding
3036 ans = Decimal(self._exp + len(self._int) - 1)
3037 else:
3038 # result is irrational, so necessarily inexact
3039 op = _WorkRep(self)
3040 c, e = op.int, op.exp
3041 p = context.prec
3042
3043 # correctly rounded result: repeatedly increase precision
3044 # until result is unambiguously roundable
3045 places = p-self._log10_exp_bound()+2
3046 while True:
3047 coeff = _dlog10(c, e, places)
3048 # assert len(str(abs(coeff)))-p >= 1
3049 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3050 break
3051 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003052 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003053
3054 context = context._shallow_copy()
3055 rounding = context._set_rounding(ROUND_HALF_EVEN)
3056 ans = ans._fix(context)
3057 context.rounding = rounding
3058 return ans
3059
3060 def logb(self, context=None):
3061 """ Returns the exponent of the magnitude of self's MSD.
3062
3063 The result is the integer which is the exponent of the magnitude
3064 of the most significant digit of self (as though it were truncated
3065 to a single digit while maintaining the value of that digit and
3066 without limiting the resulting exponent).
3067 """
3068 # logb(NaN) = NaN
3069 ans = self._check_nans(context=context)
3070 if ans:
3071 return ans
3072
3073 if context is None:
3074 context = getcontext()
3075
3076 # logb(+/-Inf) = +Inf
3077 if self._isinfinity():
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003078 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003079
3080 # logb(0) = -Inf, DivisionByZero
3081 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003082 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003083
3084 # otherwise, simply return the adjusted exponent of self, as a
3085 # Decimal. Note that no attempt is made to fit the result
3086 # into the current context.
3087 return Decimal(self.adjusted())
3088
3089 def _islogical(self):
3090 """Return True if self is a logical operand.
3091
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003092 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003093 an exponent of 0, and a coefficient whose digits must all be
3094 either 0 or 1.
3095 """
3096 if self._sign != 0 or self._exp != 0:
3097 return False
3098 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003099 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003100 return False
3101 return True
3102
3103 def _fill_logical(self, context, opa, opb):
3104 dif = context.prec - len(opa)
3105 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003106 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003107 elif dif < 0:
3108 opa = opa[-context.prec:]
3109 dif = context.prec - len(opb)
3110 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003111 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003112 elif dif < 0:
3113 opb = opb[-context.prec:]
3114 return opa, opb
3115
3116 def logical_and(self, other, context=None):
3117 """Applies an 'and' operation between self and other's digits."""
3118 if context is None:
3119 context = getcontext()
3120 if not self._islogical() or not other._islogical():
3121 return context._raise_error(InvalidOperation)
3122
3123 # fill to context.prec
3124 (opa, opb) = self._fill_logical(context, self._int, other._int)
3125
3126 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003127 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3128 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003129
3130 def logical_invert(self, context=None):
3131 """Invert all its digits."""
3132 if context is None:
3133 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003134 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3135 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003136
3137 def logical_or(self, other, context=None):
3138 """Applies an 'or' operation between self and other's digits."""
3139 if context is None:
3140 context = getcontext()
3141 if not self._islogical() or not other._islogical():
3142 return context._raise_error(InvalidOperation)
3143
3144 # fill to context.prec
3145 (opa, opb) = self._fill_logical(context, self._int, other._int)
3146
3147 # make the operation, and clean starting zeroes
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00003148 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003149 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003150
3151 def logical_xor(self, other, context=None):
3152 """Applies an 'xor' operation between self and other's digits."""
3153 if context is None:
3154 context = getcontext()
3155 if not self._islogical() or not other._islogical():
3156 return context._raise_error(InvalidOperation)
3157
3158 # fill to context.prec
3159 (opa, opb) = self._fill_logical(context, self._int, other._int)
3160
3161 # make the operation, and clean starting zeroes
Mark Dickinsonc95c6f12009-01-04 21:30:17 +00003162 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
Facundo Batista72bc54f2007-11-23 17:59:00 +00003163 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003164
3165 def max_mag(self, other, context=None):
3166 """Compares the values numerically with their sign ignored."""
3167 other = _convert_other(other, raiseit=True)
3168
Facundo Batista6c398da2007-09-17 17:30:13 +00003169 if context is None:
3170 context = getcontext()
3171
Facundo Batista353750c2007-09-13 18:13:15 +00003172 if self._is_special or other._is_special:
3173 # If one operand is a quiet NaN and the other is number, then the
3174 # number is always returned
3175 sn = self._isnan()
3176 on = other._isnan()
3177 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00003178 if on == 1 and sn == 0:
3179 return self._fix(context)
3180 if sn == 1 and on == 0:
3181 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003182 return self._check_nans(other, context)
3183
Mark Dickinson2fc92632008-02-06 22:10:50 +00003184 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003185 if c == 0:
3186 c = self.compare_total(other)
3187
3188 if c == -1:
3189 ans = other
3190 else:
3191 ans = self
3192
Facundo Batistae64acfa2007-12-17 14:18:42 +00003193 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003194
3195 def min_mag(self, other, context=None):
3196 """Compares the values numerically with their sign ignored."""
3197 other = _convert_other(other, raiseit=True)
3198
Facundo Batista6c398da2007-09-17 17:30:13 +00003199 if context is None:
3200 context = getcontext()
3201
Facundo Batista353750c2007-09-13 18:13:15 +00003202 if self._is_special or other._is_special:
3203 # If one operand is a quiet NaN and the other is number, then the
3204 # number is always returned
3205 sn = self._isnan()
3206 on = other._isnan()
3207 if sn or on:
Mark Dickinson7c62f892008-12-11 09:17:40 +00003208 if on == 1 and sn == 0:
3209 return self._fix(context)
3210 if sn == 1 and on == 0:
3211 return other._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003212 return self._check_nans(other, context)
3213
Mark Dickinson2fc92632008-02-06 22:10:50 +00003214 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003215 if c == 0:
3216 c = self.compare_total(other)
3217
3218 if c == -1:
3219 ans = self
3220 else:
3221 ans = other
3222
Facundo Batistae64acfa2007-12-17 14:18:42 +00003223 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003224
3225 def next_minus(self, context=None):
3226 """Returns the largest representable number smaller than itself."""
3227 if context is None:
3228 context = getcontext()
3229
3230 ans = self._check_nans(context=context)
3231 if ans:
3232 return ans
3233
3234 if self._isinfinity() == -1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003235 return _NegativeInfinity
Facundo Batista353750c2007-09-13 18:13:15 +00003236 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003237 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003238
3239 context = context.copy()
3240 context._set_rounding(ROUND_FLOOR)
3241 context._ignore_all_flags()
3242 new_self = self._fix(context)
3243 if new_self != self:
3244 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003245 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3246 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003247
3248 def next_plus(self, context=None):
3249 """Returns the smallest representable number larger than itself."""
3250 if context is None:
3251 context = getcontext()
3252
3253 ans = self._check_nans(context=context)
3254 if ans:
3255 return ans
3256
3257 if self._isinfinity() == 1:
Mark Dickinsone4d46b22009-01-03 12:09:22 +00003258 return _Infinity
Facundo Batista353750c2007-09-13 18:13:15 +00003259 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003260 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003261
3262 context = context.copy()
3263 context._set_rounding(ROUND_CEILING)
3264 context._ignore_all_flags()
3265 new_self = self._fix(context)
3266 if new_self != self:
3267 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003268 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3269 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003270
3271 def next_toward(self, other, context=None):
3272 """Returns the number closest to self, in the direction towards other.
3273
3274 The result is the closest representable number to self
3275 (excluding self) that is in the direction towards other,
3276 unless both have the same value. If the two operands are
3277 numerically equal, then the result is a copy of self with the
3278 sign set to be the same as the sign of other.
3279 """
3280 other = _convert_other(other, raiseit=True)
3281
3282 if context is None:
3283 context = getcontext()
3284
3285 ans = self._check_nans(other, context)
3286 if ans:
3287 return ans
3288
Mark Dickinson2fc92632008-02-06 22:10:50 +00003289 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003290 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003291 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003292
3293 if comparison == -1:
3294 ans = self.next_plus(context)
3295 else: # comparison == 1
3296 ans = self.next_minus(context)
3297
3298 # decide which flags to raise using value of ans
3299 if ans._isinfinity():
3300 context._raise_error(Overflow,
3301 'Infinite result from next_toward',
3302 ans._sign)
3303 context._raise_error(Rounded)
3304 context._raise_error(Inexact)
3305 elif ans.adjusted() < context.Emin:
3306 context._raise_error(Underflow)
3307 context._raise_error(Subnormal)
3308 context._raise_error(Rounded)
3309 context._raise_error(Inexact)
3310 # if precision == 1 then we don't raise Clamped for a
3311 # result 0E-Etiny.
3312 if not ans:
3313 context._raise_error(Clamped)
3314
3315 return ans
3316
3317 def number_class(self, context=None):
3318 """Returns an indication of the class of self.
3319
3320 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003321 sNaN
3322 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003323 -Infinity
3324 -Normal
3325 -Subnormal
3326 -Zero
3327 +Zero
3328 +Subnormal
3329 +Normal
3330 +Infinity
3331 """
3332 if self.is_snan():
3333 return "sNaN"
3334 if self.is_qnan():
3335 return "NaN"
3336 inf = self._isinfinity()
3337 if inf == 1:
3338 return "+Infinity"
3339 if inf == -1:
3340 return "-Infinity"
3341 if self.is_zero():
3342 if self._sign:
3343 return "-Zero"
3344 else:
3345 return "+Zero"
3346 if context is None:
3347 context = getcontext()
3348 if self.is_subnormal(context=context):
3349 if self._sign:
3350 return "-Subnormal"
3351 else:
3352 return "+Subnormal"
3353 # just a normal, regular, boring number, :)
3354 if self._sign:
3355 return "-Normal"
3356 else:
3357 return "+Normal"
3358
3359 def radix(self):
3360 """Just returns 10, as this is Decimal, :)"""
3361 return Decimal(10)
3362
3363 def rotate(self, other, context=None):
3364 """Returns a rotated copy of self, value-of-other times."""
3365 if context is None:
3366 context = getcontext()
3367
3368 ans = self._check_nans(other, context)
3369 if ans:
3370 return ans
3371
3372 if other._exp != 0:
3373 return context._raise_error(InvalidOperation)
3374 if not (-context.prec <= int(other) <= context.prec):
3375 return context._raise_error(InvalidOperation)
3376
3377 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003378 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003379
3380 # get values, pad if necessary
3381 torot = int(other)
3382 rotdig = self._int
3383 topad = context.prec - len(rotdig)
3384 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003385 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003386
3387 # let's rotate!
3388 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003389 return _dec_from_triple(self._sign,
3390 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003391
3392 def scaleb (self, other, context=None):
3393 """Returns self operand after adding the second value to its exp."""
3394 if context is None:
3395 context = getcontext()
3396
3397 ans = self._check_nans(other, context)
3398 if ans:
3399 return ans
3400
3401 if other._exp != 0:
3402 return context._raise_error(InvalidOperation)
3403 liminf = -2 * (context.Emax + context.prec)
3404 limsup = 2 * (context.Emax + context.prec)
3405 if not (liminf <= int(other) <= limsup):
3406 return context._raise_error(InvalidOperation)
3407
3408 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003409 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003410
Facundo Batista72bc54f2007-11-23 17:59:00 +00003411 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003412 d = d._fix(context)
3413 return d
3414
3415 def shift(self, other, context=None):
3416 """Returns a shifted copy of self, value-of-other times."""
3417 if context is None:
3418 context = getcontext()
3419
3420 ans = self._check_nans(other, context)
3421 if ans:
3422 return ans
3423
3424 if other._exp != 0:
3425 return context._raise_error(InvalidOperation)
3426 if not (-context.prec <= int(other) <= context.prec):
3427 return context._raise_error(InvalidOperation)
3428
3429 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003430 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003431
3432 # get values, pad if necessary
3433 torot = int(other)
3434 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003435 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003436 rotdig = self._int
3437 topad = context.prec - len(rotdig)
3438 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003439 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003440
3441 # let's shift!
3442 if torot < 0:
3443 rotated = rotdig[:torot]
3444 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003445 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003446 rotated = rotated[-context.prec:]
3447
Facundo Batista72bc54f2007-11-23 17:59:00 +00003448 return _dec_from_triple(self._sign,
3449 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003450
Facundo Batista59c58842007-04-10 12:58:45 +00003451 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003452 def __reduce__(self):
3453 return (self.__class__, (str(self),))
3454
3455 def __copy__(self):
3456 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003457 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003458 return self.__class__(str(self))
3459
3460 def __deepcopy__(self, memo):
3461 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003462 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003463 return self.__class__(str(self))
3464
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003465 # PEP 3101 support. See also _parse_format_specifier and _format_align
3466 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003467 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003468
3469 The specifier should be a standard format specifier, with the
3470 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3471 'F', 'g', 'G', and '%' are supported. If the formatting type
3472 is omitted it defaults to 'g' or 'G', depending on the value
3473 of context.capitals.
3474
3475 At this time the 'n' format specifier type (which is supposed
3476 to use the current locale) is not supported.
3477 """
3478
3479 # Note: PEP 3101 says that if the type is not present then
3480 # there should be at least one digit after the decimal point.
3481 # We take the liberty of ignoring this requirement for
3482 # Decimal---it's presumably there to make sure that
3483 # format(float, '') behaves similarly to str(float).
3484 if context is None:
3485 context = getcontext()
3486
3487 spec = _parse_format_specifier(specifier)
3488
3489 # special values don't care about the type or precision...
3490 if self._is_special:
3491 return _format_align(str(self), spec)
3492
3493 # a type of None defaults to 'g' or 'G', depending on context
3494 # if type is '%', adjust exponent of self accordingly
3495 if spec['type'] is None:
3496 spec['type'] = ['g', 'G'][context.capitals]
3497 elif spec['type'] == '%':
3498 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3499
3500 # round if necessary, taking rounding mode from the context
3501 rounding = context.rounding
3502 precision = spec['precision']
3503 if precision is not None:
3504 if spec['type'] in 'eE':
3505 self = self._round(precision+1, rounding)
3506 elif spec['type'] in 'gG':
3507 if len(self._int) > precision:
3508 self = self._round(precision, rounding)
3509 elif spec['type'] in 'fF%':
3510 self = self._rescale(-precision, rounding)
3511 # special case: zeros with a positive exponent can't be
3512 # represented in fixed point; rescale them to 0e0.
3513 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3514 self = self._rescale(0, rounding)
3515
3516 # figure out placement of the decimal point
3517 leftdigits = self._exp + len(self._int)
3518 if spec['type'] in 'fF%':
3519 dotplace = leftdigits
3520 elif spec['type'] in 'eE':
3521 if not self and precision is not None:
3522 dotplace = 1 - precision
3523 else:
3524 dotplace = 1
3525 elif spec['type'] in 'gG':
3526 if self._exp <= 0 and leftdigits > -6:
3527 dotplace = leftdigits
3528 else:
3529 dotplace = 1
3530
3531 # figure out main part of numeric string...
3532 if dotplace <= 0:
3533 num = '0.' + '0'*(-dotplace) + self._int
3534 elif dotplace >= len(self._int):
3535 # make sure we're not padding a '0' with extra zeros on the right
3536 assert dotplace==len(self._int) or self._int != '0'
3537 num = self._int + '0'*(dotplace-len(self._int))
3538 else:
3539 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3540
3541 # ...then the trailing exponent, or trailing '%'
3542 if leftdigits != dotplace or spec['type'] in 'eE':
3543 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3544 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3545 elif spec['type'] == '%':
3546 num = num + '%'
3547
3548 # add sign
3549 if self._sign == 1:
3550 num = '-' + num
3551 return _format_align(num, spec)
3552
3553
Facundo Batista72bc54f2007-11-23 17:59:00 +00003554def _dec_from_triple(sign, coefficient, exponent, special=False):
3555 """Create a decimal instance directly, without any validation,
3556 normalization (e.g. removal of leading zeros) or argument
3557 conversion.
3558
3559 This function is for *internal use only*.
3560 """
3561
3562 self = object.__new__(Decimal)
3563 self._sign = sign
3564 self._int = coefficient
3565 self._exp = exponent
3566 self._is_special = special
3567
3568 return self
3569
Facundo Batista59c58842007-04-10 12:58:45 +00003570##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003571
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003572
3573# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003574rounding_functions = [name for name in Decimal.__dict__.keys()
3575 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003576for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003577 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003578 globalname = name[1:].upper()
3579 val = globals()[globalname]
3580 Decimal._pick_rounding_function[val] = name
3581
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003582del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003583
Nick Coghlanced12182006-09-02 03:54:17 +00003584class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003585 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003586
Nick Coghlanced12182006-09-02 03:54:17 +00003587 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003588 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003589 """
3590 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003591 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003592 def __enter__(self):
3593 self.saved_context = getcontext()
3594 setcontext(self.new_context)
3595 return self.new_context
3596 def __exit__(self, t, v, tb):
3597 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003598
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003599class Context(object):
3600 """Contains the context for a Decimal instance.
3601
3602 Contains:
3603 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003604 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003605 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 raised when it is caused. Otherwise, a value is
3607 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003608 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003609 (Whether or not the trap_enabler is set)
3610 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003611 Emin - Minimum exponent
3612 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003613 capitals - If 1, 1*10^1 is printed as 1E+1.
3614 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003615 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003616 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003617
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003618 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003619 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003620 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003621 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003622 _ignored_flags=None):
3623 if flags is None:
3624 flags = []
3625 if _ignored_flags is None:
3626 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003627 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003628 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003629 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003630 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003631 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003632 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003633 for name, val in locals().items():
3634 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003635 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003636 else:
3637 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003638 del self.self
3639
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003640 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003641 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003642 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003643 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3644 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3645 % vars(self))
3646 names = [f.__name__ for f, v in self.flags.items() if v]
3647 s.append('flags=[' + ', '.join(names) + ']')
3648 names = [t.__name__ for t, v in self.traps.items() if v]
3649 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003650 return ', '.join(s) + ')'
3651
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003652 def clear_flags(self):
3653 """Reset all flags to zero"""
3654 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003655 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003656
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003657 def _shallow_copy(self):
3658 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003659 nc = Context(self.prec, self.rounding, self.traps,
3660 self.flags, self.Emin, self.Emax,
3661 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003662 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003663
3664 def copy(self):
3665 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003666 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003667 self.flags.copy(), self.Emin, self.Emax,
3668 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003669 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003670 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003671
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003672 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003673 """Handles an error
3674
3675 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003676 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003678 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003679 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003680 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003682 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003683 return error().handle(self, *args)
3684
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003685 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003686 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003687 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003688 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689
3690 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003691 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003692 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003693
3694 def _ignore_all_flags(self):
3695 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003696 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003697
3698 def _ignore_flags(self, *flags):
3699 """Ignore the flags, if they are raised"""
3700 # Do not mutate-- This way, copies of a context leave the original
3701 # alone.
3702 self._ignored_flags = (self._ignored_flags + list(flags))
3703 return list(flags)
3704
3705 def _regard_flags(self, *flags):
3706 """Stop ignoring the flags, if they are raised"""
3707 if flags and isinstance(flags[0], (tuple,list)):
3708 flags = flags[0]
3709 for flag in flags:
3710 self._ignored_flags.remove(flag)
3711
Nick Coghlan53663a62008-07-15 14:27:37 +00003712 # We inherit object.__hash__, so we must deny this explicitly
3713 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003714
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715 def Etiny(self):
3716 """Returns Etiny (= Emin - prec + 1)"""
3717 return int(self.Emin - self.prec + 1)
3718
3719 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003720 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003721 return int(self.Emax - self.prec + 1)
3722
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003723 def _set_rounding(self, type):
3724 """Sets the rounding type.
3725
3726 Sets the rounding type, and returns the current (previous)
3727 rounding type. Often used like:
3728
3729 context = context.copy()
3730 # so you don't change the calling context
3731 # if an error occurs in the middle.
3732 rounding = context._set_rounding(ROUND_UP)
3733 val = self.__sub__(other, context=context)
3734 context._set_rounding(rounding)
3735
3736 This will make it round up for that operation.
3737 """
3738 rounding = self.rounding
3739 self.rounding= type
3740 return rounding
3741
Raymond Hettingerfed52962004-07-14 15:41:57 +00003742 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003743 """Creates a new Decimal instance but using self as context.
3744
3745 This method implements the to-number operation of the
3746 IBM Decimal specification."""
3747
3748 if isinstance(num, basestring) and num != num.strip():
3749 return self._raise_error(ConversionSyntax,
3750 "no trailing or leading whitespace is "
3751 "permitted.")
3752
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003754 if d._isnan() and len(d._int) > self.prec - self._clamp:
3755 return self._raise_error(ConversionSyntax,
3756 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003757 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003758
Facundo Batista59c58842007-04-10 12:58:45 +00003759 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003760 def abs(self, a):
3761 """Returns the absolute value of the operand.
3762
3763 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003764 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003765 the plus operation on the operand.
3766
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003767 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003768 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003769 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003770 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003771 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003772 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003773 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003774 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003775 """
3776 return a.__abs__(context=self)
3777
3778 def add(self, a, b):
3779 """Return the sum of the two operands.
3780
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003781 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003782 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003783 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003784 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003785 """
3786 return a.__add__(b, context=self)
3787
3788 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003789 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790
Facundo Batista353750c2007-09-13 18:13:15 +00003791 def canonical(self, a):
3792 """Returns the same Decimal object.
3793
3794 As we do not have different encodings for the same number, the
3795 received object already is in its canonical form.
3796
3797 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003798 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003799 """
3800 return a.canonical(context=self)
3801
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003802 def compare(self, a, b):
3803 """Compares values numerically.
3804
3805 If the signs of the operands differ, a value representing each operand
3806 ('-1' if the operand is less than zero, '0' if the operand is zero or
3807 negative zero, or '1' if the operand is greater than zero) is used in
3808 place of that operand for the comparison instead of the actual
3809 operand.
3810
3811 The comparison is then effected by subtracting the second operand from
3812 the first and then returning a value according to the result of the
3813 subtraction: '-1' if the result is less than zero, '0' if the result is
3814 zero or negative zero, or '1' if the result is greater than zero.
3815
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003817 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003819 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003821 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003822 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003823 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003824 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003825 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003826 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003827 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003828 """
3829 return a.compare(b, context=self)
3830
Facundo Batista353750c2007-09-13 18:13:15 +00003831 def compare_signal(self, a, b):
3832 """Compares the values of the two operands numerically.
3833
3834 It's pretty much like compare(), but all NaNs signal, with signaling
3835 NaNs taking precedence over quiet NaNs.
3836
3837 >>> c = ExtendedContext
3838 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003839 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003840 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003841 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003842 >>> c.flags[InvalidOperation] = 0
3843 >>> print c.flags[InvalidOperation]
3844 0
3845 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003846 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003847 >>> print c.flags[InvalidOperation]
3848 1
3849 >>> c.flags[InvalidOperation] = 0
3850 >>> print c.flags[InvalidOperation]
3851 0
3852 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003853 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003854 >>> print c.flags[InvalidOperation]
3855 1
3856 """
3857 return a.compare_signal(b, context=self)
3858
3859 def compare_total(self, a, b):
3860 """Compares two operands using their abstract representation.
3861
3862 This is not like the standard compare, which use their numerical
3863 value. Note that a total ordering is defined for all possible abstract
3864 representations.
3865
3866 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003867 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003868 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003869 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003870 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003871 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003872 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003873 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003874 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003875 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003876 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003877 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003878 """
3879 return a.compare_total(b)
3880
3881 def compare_total_mag(self, a, b):
3882 """Compares two operands using their abstract representation ignoring sign.
3883
3884 Like compare_total, but with operand's sign ignored and assumed to be 0.
3885 """
3886 return a.compare_total_mag(b)
3887
3888 def copy_abs(self, a):
3889 """Returns a copy of the operand with the sign set to 0.
3890
3891 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003892 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003893 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003894 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003895 """
3896 return a.copy_abs()
3897
3898 def copy_decimal(self, a):
3899 """Returns a copy of the decimal objet.
3900
3901 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003902 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003903 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003904 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003905 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003906 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003907
3908 def copy_negate(self, a):
3909 """Returns a copy of the operand with the sign inverted.
3910
3911 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003912 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003913 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003914 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003915 """
3916 return a.copy_negate()
3917
3918 def copy_sign(self, a, b):
3919 """Copies the second operand's sign to the first one.
3920
3921 In detail, it returns a copy of the first operand with the sign
3922 equal to the sign of the second operand.
3923
3924 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003925 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003926 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003927 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003928 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003929 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003930 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003931 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003932 """
3933 return a.copy_sign(b)
3934
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003935 def divide(self, a, b):
3936 """Decimal division in a specified context.
3937
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003938 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003939 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003940 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003941 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003942 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003943 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003944 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003945 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003946 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003947 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003948 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003949 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003950 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003951 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003952 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003953 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003954 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003955 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003956 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003957 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003958 """
3959 return a.__div__(b, context=self)
3960
3961 def divide_int(self, a, b):
3962 """Divides two numbers and returns the integer part of the result.
3963
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003964 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003965 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003966 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003967 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003968 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003969 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003970 """
3971 return a.__floordiv__(b, context=self)
3972
3973 def divmod(self, a, b):
3974 return a.__divmod__(b, context=self)
3975
Facundo Batista353750c2007-09-13 18:13:15 +00003976 def exp(self, a):
3977 """Returns e ** a.
3978
3979 >>> c = ExtendedContext.copy()
3980 >>> c.Emin = -999
3981 >>> c.Emax = 999
3982 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003983 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003984 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00003986 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003987 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003988 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003989 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00003990 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003991 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00003992 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003993 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00003994 """
3995 return a.exp(context=self)
3996
3997 def fma(self, a, b, c):
3998 """Returns a multiplied by b, plus c.
3999
4000 The first two operands are multiplied together, using multiply,
4001 the third operand is then added to the result of that
4002 multiplication, using add, all with only one final rounding.
4003
4004 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004005 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004006 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004007 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004008 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004009 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004010 """
4011 return a.fma(b, c, context=self)
4012
4013 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004014 """Return True if the operand is canonical; otherwise return False.
4015
4016 Currently, the encoding of a Decimal instance is always
4017 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004018
4019 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004020 True
Facundo Batista353750c2007-09-13 18:13:15 +00004021 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004022 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004023
4024 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004025 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004026
Facundo Batista1a191df2007-10-02 17:01:24 +00004027 A Decimal instance is considered finite if it is neither
4028 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004029
4030 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004031 True
Facundo Batista353750c2007-09-13 18:13:15 +00004032 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004033 True
Facundo Batista353750c2007-09-13 18:13:15 +00004034 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004035 True
Facundo Batista353750c2007-09-13 18:13:15 +00004036 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004037 False
Facundo Batista353750c2007-09-13 18:13:15 +00004038 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004039 False
Facundo Batista353750c2007-09-13 18:13:15 +00004040 """
4041 return a.is_finite()
4042
4043 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004044 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004045
4046 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004047 False
Facundo Batista353750c2007-09-13 18:13:15 +00004048 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004049 True
Facundo Batista353750c2007-09-13 18:13:15 +00004050 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004051 False
Facundo Batista353750c2007-09-13 18:13:15 +00004052 """
4053 return a.is_infinite()
4054
4055 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004056 """Return True if the operand is a qNaN or sNaN;
4057 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004058
4059 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004060 False
Facundo Batista353750c2007-09-13 18:13:15 +00004061 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004062 True
Facundo Batista353750c2007-09-13 18:13:15 +00004063 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004064 True
Facundo Batista353750c2007-09-13 18:13:15 +00004065 """
4066 return a.is_nan()
4067
4068 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004069 """Return True if the operand is a normal number;
4070 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004071
4072 >>> c = ExtendedContext.copy()
4073 >>> c.Emin = -999
4074 >>> c.Emax = 999
4075 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004076 True
Facundo Batista353750c2007-09-13 18:13:15 +00004077 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004078 False
Facundo Batista353750c2007-09-13 18:13:15 +00004079 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004080 False
Facundo Batista353750c2007-09-13 18:13:15 +00004081 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004082 False
Facundo Batista353750c2007-09-13 18:13:15 +00004083 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004084 False
Facundo Batista353750c2007-09-13 18:13:15 +00004085 """
4086 return a.is_normal(context=self)
4087
4088 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004089 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004090
4091 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004092 False
Facundo Batista353750c2007-09-13 18:13:15 +00004093 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004094 True
Facundo Batista353750c2007-09-13 18:13:15 +00004095 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004096 False
Facundo Batista353750c2007-09-13 18:13:15 +00004097 """
4098 return a.is_qnan()
4099
4100 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004101 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004102
4103 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004104 False
Facundo Batista353750c2007-09-13 18:13:15 +00004105 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004106 True
Facundo Batista353750c2007-09-13 18:13:15 +00004107 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004108 True
Facundo Batista353750c2007-09-13 18:13:15 +00004109 """
4110 return a.is_signed()
4111
4112 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004113 """Return True if the operand is a signaling NaN;
4114 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004115
4116 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004117 False
Facundo Batista353750c2007-09-13 18:13:15 +00004118 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004119 False
Facundo Batista353750c2007-09-13 18:13:15 +00004120 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004121 True
Facundo Batista353750c2007-09-13 18:13:15 +00004122 """
4123 return a.is_snan()
4124
4125 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004126 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004127
4128 >>> c = ExtendedContext.copy()
4129 >>> c.Emin = -999
4130 >>> c.Emax = 999
4131 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004132 False
Facundo Batista353750c2007-09-13 18:13:15 +00004133 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004134 True
Facundo Batista353750c2007-09-13 18:13:15 +00004135 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004136 False
Facundo Batista353750c2007-09-13 18:13:15 +00004137 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004138 False
Facundo Batista353750c2007-09-13 18:13:15 +00004139 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004140 False
Facundo Batista353750c2007-09-13 18:13:15 +00004141 """
4142 return a.is_subnormal(context=self)
4143
4144 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004145 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004146
4147 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004148 True
Facundo Batista353750c2007-09-13 18:13:15 +00004149 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004150 False
Facundo Batista353750c2007-09-13 18:13:15 +00004151 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004152 True
Facundo Batista353750c2007-09-13 18:13:15 +00004153 """
4154 return a.is_zero()
4155
4156 def ln(self, a):
4157 """Returns the natural (base e) logarithm of the operand.
4158
4159 >>> c = ExtendedContext.copy()
4160 >>> c.Emin = -999
4161 >>> c.Emax = 999
4162 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004163 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004164 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004165 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004166 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004167 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004168 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004169 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004170 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004171 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004172 """
4173 return a.ln(context=self)
4174
4175 def log10(self, a):
4176 """Returns the base 10 logarithm of the operand.
4177
4178 >>> c = ExtendedContext.copy()
4179 >>> c.Emin = -999
4180 >>> c.Emax = 999
4181 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004182 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004183 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004184 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004185 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004186 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004187 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004188 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004189 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004190 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004191 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004192 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004193 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004194 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004195 """
4196 return a.log10(context=self)
4197
4198 def logb(self, a):
4199 """ Returns the exponent of the magnitude of the operand's MSD.
4200
4201 The result is the integer which is the exponent of the magnitude
4202 of the most significant digit of the operand (as though the
4203 operand were truncated to a single digit while maintaining the
4204 value of that digit and without limiting the resulting exponent).
4205
4206 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004207 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004208 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004209 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004210 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004211 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004212 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004213 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004214 """
4215 return a.logb(context=self)
4216
4217 def logical_and(self, a, b):
4218 """Applies the logical operation 'and' between each operand's digits.
4219
4220 The operands must be both logical numbers.
4221
4222 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004223 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004224 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004225 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004226 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004227 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004228 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004229 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004230 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004231 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004232 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004233 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004234 """
4235 return a.logical_and(b, context=self)
4236
4237 def logical_invert(self, a):
4238 """Invert all the digits in the operand.
4239
4240 The operand must be a logical number.
4241
4242 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004243 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004244 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004245 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004246 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004247 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004248 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004249 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004250 """
4251 return a.logical_invert(context=self)
4252
4253 def logical_or(self, a, b):
4254 """Applies the logical operation 'or' between each operand's digits.
4255
4256 The operands must be both logical numbers.
4257
4258 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004259 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004260 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004261 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004262 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004263 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004264 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004265 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004266 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004267 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004268 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004269 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004270 """
4271 return a.logical_or(b, context=self)
4272
4273 def logical_xor(self, a, b):
4274 """Applies the logical operation 'xor' between each operand's digits.
4275
4276 The operands must be both logical numbers.
4277
4278 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004279 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004280 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004281 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004282 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004283 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004284 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004285 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004286 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004287 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004288 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004289 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004290 """
4291 return a.logical_xor(b, context=self)
4292
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004293 def max(self, a,b):
4294 """max compares two values numerically and returns the maximum.
4295
4296 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004297 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004298 operation. If they are numerically equal then the left-hand operand
4299 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004300 infinity) of the two operands is chosen as the result.
4301
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004302 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004303 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004304 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004305 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004306 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004307 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004308 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004309 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004310 """
4311 return a.max(b, context=self)
4312
Facundo Batista353750c2007-09-13 18:13:15 +00004313 def max_mag(self, a, b):
4314 """Compares the values numerically with their sign ignored."""
4315 return a.max_mag(b, context=self)
4316
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004317 def min(self, a,b):
4318 """min compares two values numerically and returns the minimum.
4319
4320 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004321 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004322 operation. If they are numerically equal then the left-hand operand
4323 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004324 infinity) of the two operands is chosen as the result.
4325
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004326 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004327 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004328 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004329 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004330 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004331 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004332 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004333 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004334 """
4335 return a.min(b, context=self)
4336
Facundo Batista353750c2007-09-13 18:13:15 +00004337 def min_mag(self, a, b):
4338 """Compares the values numerically with their sign ignored."""
4339 return a.min_mag(b, context=self)
4340
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004341 def minus(self, a):
4342 """Minus corresponds to unary prefix minus in Python.
4343
4344 The operation is evaluated using the same rules as subtract; the
4345 operation minus(a) is calculated as subtract('0', a) where the '0'
4346 has the same exponent as the operand.
4347
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004348 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004349 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004350 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004351 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004352 """
4353 return a.__neg__(context=self)
4354
4355 def multiply(self, a, b):
4356 """multiply multiplies two operands.
4357
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004358 If either operand is a special value then the general rules apply.
4359 Otherwise, the operands are multiplied together ('long multiplication'),
4360 resulting in a number which may be as long as the sum of the lengths
4361 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004362
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004364 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004366 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004367 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004368 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004369 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004370 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004371 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004372 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004373 """
4374 return a.__mul__(b, context=self)
4375
Facundo Batista353750c2007-09-13 18:13:15 +00004376 def next_minus(self, a):
4377 """Returns the largest representable number smaller than a.
4378
4379 >>> c = ExtendedContext.copy()
4380 >>> c.Emin = -999
4381 >>> c.Emax = 999
4382 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004383 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004384 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004385 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004386 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004387 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004388 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004389 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004390 """
4391 return a.next_minus(context=self)
4392
4393 def next_plus(self, a):
4394 """Returns the smallest representable number larger than a.
4395
4396 >>> c = ExtendedContext.copy()
4397 >>> c.Emin = -999
4398 >>> c.Emax = 999
4399 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004400 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004401 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004402 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004403 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004404 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004405 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004406 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004407 """
4408 return a.next_plus(context=self)
4409
4410 def next_toward(self, a, b):
4411 """Returns the number closest to a, in direction towards b.
4412
4413 The result is the closest representable number from the first
4414 operand (but not the first operand) that is in the direction
4415 towards the second operand, unless the operands have the same
4416 value.
4417
4418 >>> c = ExtendedContext.copy()
4419 >>> c.Emin = -999
4420 >>> c.Emax = 999
4421 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004422 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004423 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004424 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004425 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004426 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004428 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004429 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004430 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004431 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004432 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004433 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004434 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004435 """
4436 return a.next_toward(b, context=self)
4437
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004438 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004439 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004440
4441 Essentially a plus operation with all trailing zeros removed from the
4442 result.
4443
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004445 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004447 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004449 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004450 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004451 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004452 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004453 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004454 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004455 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004456 """
4457 return a.normalize(context=self)
4458
Facundo Batista353750c2007-09-13 18:13:15 +00004459 def number_class(self, a):
4460 """Returns an indication of the class of the operand.
4461
4462 The class is one of the following strings:
4463 -sNaN
4464 -NaN
4465 -Infinity
4466 -Normal
4467 -Subnormal
4468 -Zero
4469 +Zero
4470 +Subnormal
4471 +Normal
4472 +Infinity
4473
4474 >>> c = Context(ExtendedContext)
4475 >>> c.Emin = -999
4476 >>> c.Emax = 999
4477 >>> c.number_class(Decimal('Infinity'))
4478 '+Infinity'
4479 >>> c.number_class(Decimal('1E-10'))
4480 '+Normal'
4481 >>> c.number_class(Decimal('2.50'))
4482 '+Normal'
4483 >>> c.number_class(Decimal('0.1E-999'))
4484 '+Subnormal'
4485 >>> c.number_class(Decimal('0'))
4486 '+Zero'
4487 >>> c.number_class(Decimal('-0'))
4488 '-Zero'
4489 >>> c.number_class(Decimal('-0.1E-999'))
4490 '-Subnormal'
4491 >>> c.number_class(Decimal('-1E-10'))
4492 '-Normal'
4493 >>> c.number_class(Decimal('-2.50'))
4494 '-Normal'
4495 >>> c.number_class(Decimal('-Infinity'))
4496 '-Infinity'
4497 >>> c.number_class(Decimal('NaN'))
4498 'NaN'
4499 >>> c.number_class(Decimal('-NaN'))
4500 'NaN'
4501 >>> c.number_class(Decimal('sNaN'))
4502 'sNaN'
4503 """
4504 return a.number_class(context=self)
4505
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004506 def plus(self, a):
4507 """Plus corresponds to unary prefix plus in Python.
4508
4509 The operation is evaluated using the same rules as add; the
4510 operation plus(a) is calculated as add('0', a) where the '0'
4511 has the same exponent as the operand.
4512
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004513 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004514 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004515 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004516 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004517 """
4518 return a.__pos__(context=self)
4519
4520 def power(self, a, b, modulo=None):
4521 """Raises a to the power of b, to modulo if given.
4522
Facundo Batista353750c2007-09-13 18:13:15 +00004523 With two arguments, compute a**b. If a is negative then b
4524 must be integral. The result will be inexact unless b is
4525 integral and the result is finite and can be expressed exactly
4526 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004527
Facundo Batista353750c2007-09-13 18:13:15 +00004528 With three arguments, compute (a**b) % modulo. For the
4529 three argument form, the following restrictions on the
4530 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004531
Facundo Batista353750c2007-09-13 18:13:15 +00004532 - all three arguments must be integral
4533 - b must be nonnegative
4534 - at least one of a or b must be nonzero
4535 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004536
Facundo Batista353750c2007-09-13 18:13:15 +00004537 The result of pow(a, b, modulo) is identical to the result
4538 that would be obtained by computing (a**b) % modulo with
4539 unbounded precision, but is computed more efficiently. It is
4540 always exact.
4541
4542 >>> c = ExtendedContext.copy()
4543 >>> c.Emin = -999
4544 >>> c.Emax = 999
4545 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004546 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004547 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004548 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004549 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004550 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004551 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004552 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004553 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004554 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004555 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004556 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004557 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004558 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004559 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004560 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004561 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004562 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004563 >>> c.power(Decimal('-Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004564 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004565 >>> c.power(Decimal('-Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004566 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004567 >>> c.power(Decimal('-Infinity'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004568 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004569 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004570 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004571
4572 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004573 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004574 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004575 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004576 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004577 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004578 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004579 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004580 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004581 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004582 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004583 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004584 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004585 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004586 """
4587 return a.__pow__(b, modulo, context=self)
4588
4589 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004590 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004591
4592 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004593 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004594 exponent is being increased), multiplied by a positive power of ten (if
4595 the exponent is being decreased), or is unchanged (if the exponent is
4596 already equal to that of the right-hand operand).
4597
4598 Unlike other operations, if the length of the coefficient after the
4599 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004600 operation condition is raised. This guarantees that, unless there is
4601 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004602 equal to that of the right-hand operand.
4603
4604 Also unlike other operations, quantize will never raise Underflow, even
4605 if the result is subnormal and inexact.
4606
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004609 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004610 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004611 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004612 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004613 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004614 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004615 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004616 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004617 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004618 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004619 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004620 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004621 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004622 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004624 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004625 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004626 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004628 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004630 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004631 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004632 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004633 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004634 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004635 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004636 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004637 """
4638 return a.quantize(b, context=self)
4639
Facundo Batista353750c2007-09-13 18:13:15 +00004640 def radix(self):
4641 """Just returns 10, as this is Decimal, :)
4642
4643 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004644 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004645 """
4646 return Decimal(10)
4647
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004648 def remainder(self, a, b):
4649 """Returns the remainder from integer division.
4650
4651 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004652 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004653 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004654 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004655
4656 This operation will fail under the same conditions as integer division
4657 (that is, if integer division on the same two operands would fail, the
4658 remainder cannot be calculated).
4659
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004661 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004663 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004665 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004666 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004667 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004668 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004669 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004670 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004671 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004672 """
4673 return a.__mod__(b, context=self)
4674
4675 def remainder_near(self, a, b):
4676 """Returns to be "a - b * n", where n is the integer nearest the exact
4677 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004678 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004679 sign of a.
4680
4681 This operation will fail under the same conditions as integer division
4682 (that is, if integer division on the same two operands would fail, the
4683 remainder cannot be calculated).
4684
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004685 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004686 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004687 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004688 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004689 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004690 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004691 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004692 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004693 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004694 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004695 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004696 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004697 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004698 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004699 """
4700 return a.remainder_near(b, context=self)
4701
Facundo Batista353750c2007-09-13 18:13:15 +00004702 def rotate(self, a, b):
4703 """Returns a rotated copy of a, b times.
4704
4705 The coefficient of the result is a rotated copy of the digits in
4706 the coefficient of the first operand. The number of places of
4707 rotation is taken from the absolute value of the second operand,
4708 with the rotation being to the left if the second operand is
4709 positive or to the right otherwise.
4710
4711 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004712 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004713 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004714 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004715 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004716 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004717 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004718 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004719 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004720 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004721 """
4722 return a.rotate(b, context=self)
4723
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004724 def same_quantum(self, a, b):
4725 """Returns True if the two operands have the same exponent.
4726
4727 The result is never affected by either the sign or the coefficient of
4728 either operand.
4729
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004730 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004732 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004733 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004734 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004735 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004736 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004737 True
4738 """
4739 return a.same_quantum(b)
4740
Facundo Batista353750c2007-09-13 18:13:15 +00004741 def scaleb (self, a, b):
4742 """Returns the first operand after adding the second value its exp.
4743
4744 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004745 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004746 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004747 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004748 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004749 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004750 """
4751 return a.scaleb (b, context=self)
4752
4753 def shift(self, a, b):
4754 """Returns a shifted copy of a, b times.
4755
4756 The coefficient of the result is a shifted copy of the digits
4757 in the coefficient of the first operand. The number of places
4758 to shift is taken from the absolute value of the second operand,
4759 with the shift being to the left if the second operand is
4760 positive or to the right otherwise. Digits shifted into the
4761 coefficient are zeros.
4762
4763 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004764 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004765 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004766 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004767 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004768 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004769 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004770 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004771 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004772 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004773 """
4774 return a.shift(b, context=self)
4775
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004776 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004777 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004778
4779 If the result must be inexact, it is rounded using the round-half-even
4780 algorithm.
4781
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004782 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004784 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004786 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004787 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004788 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004789 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004790 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004791 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004792 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004793 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004794 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004795 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004796 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004797 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004798 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004799 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004800 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004801 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 """
4803 return a.sqrt(context=self)
4804
4805 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004806 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004807
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004808 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004809 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004810 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004811 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004812 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004813 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004814 """
4815 return a.__sub__(b, context=self)
4816
4817 def to_eng_string(self, a):
4818 """Converts a number to a string, using scientific notation.
4819
4820 The operation is not affected by the context.
4821 """
4822 return a.to_eng_string(context=self)
4823
4824 def to_sci_string(self, a):
4825 """Converts a number to a string, using scientific notation.
4826
4827 The operation is not affected by the context.
4828 """
4829 return a.__str__(context=self)
4830
Facundo Batista353750c2007-09-13 18:13:15 +00004831 def to_integral_exact(self, a):
4832 """Rounds to an integer.
4833
4834 When the operand has a negative exponent, the result is the same
4835 as using the quantize() operation using the given operand as the
4836 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4837 of the operand as the precision setting; Inexact and Rounded flags
4838 are allowed in this operation. The rounding mode is taken from the
4839 context.
4840
4841 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004842 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004843 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004844 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004845 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004846 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004847 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004848 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004849 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004850 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004851 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004852 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004853 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004854 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004855 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004856 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004857 """
4858 return a.to_integral_exact(context=self)
4859
4860 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004861 """Rounds to an integer.
4862
4863 When the operand has a negative exponent, the result is the same
4864 as using the quantize() operation using the given operand as the
4865 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4866 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004867 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004868
Facundo Batista353750c2007-09-13 18:13:15 +00004869 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004870 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004871 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004872 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004873 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004874 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004875 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004876 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004877 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004878 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004879 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004880 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004881 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004882 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004883 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004884 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004885 """
Facundo Batista353750c2007-09-13 18:13:15 +00004886 return a.to_integral_value(context=self)
4887
4888 # the method name changed, but we provide also the old one, for compatibility
4889 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004890
4891class _WorkRep(object):
4892 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004893 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004894 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004895 # exp: None, int, or string
4896
4897 def __init__(self, value=None):
4898 if value is None:
4899 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004900 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004901 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004902 elif isinstance(value, Decimal):
4903 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004904 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004905 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004906 else:
4907 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004908 self.sign = value[0]
4909 self.int = value[1]
4910 self.exp = value[2]
4911
4912 def __repr__(self):
4913 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4914
4915 __str__ = __repr__
4916
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004917
4918
Facundo Batistae64acfa2007-12-17 14:18:42 +00004919def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004920 """Normalizes op1, op2 to have the same exp and length of coefficient.
4921
4922 Done during addition.
4923 """
Facundo Batista353750c2007-09-13 18:13:15 +00004924 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004925 tmp = op2
4926 other = op1
4927 else:
4928 tmp = op1
4929 other = op2
4930
Facundo Batista353750c2007-09-13 18:13:15 +00004931 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4932 # Then adding 10**exp to tmp has the same effect (after rounding)
4933 # as adding any positive quantity smaller than 10**exp; similarly
4934 # for subtraction. So if other is smaller than 10**exp we replace
4935 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004936 tmp_len = len(str(tmp.int))
4937 other_len = len(str(other.int))
4938 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4939 if other_len + other.exp - 1 < exp:
4940 other.int = 1
4941 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004942
Facundo Batista353750c2007-09-13 18:13:15 +00004943 tmp.int *= 10 ** (tmp.exp - other.exp)
4944 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004945 return op1, op2
4946
Facundo Batista353750c2007-09-13 18:13:15 +00004947##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4948
4949# This function from Tim Peters was taken from here:
4950# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4951# The correction being in the function definition is for speed, and
4952# the whole function is not resolved with math.log because of avoiding
4953# the use of floats.
4954def _nbits(n, correction = {
4955 '0': 4, '1': 3, '2': 2, '3': 2,
4956 '4': 1, '5': 1, '6': 1, '7': 1,
4957 '8': 0, '9': 0, 'a': 0, 'b': 0,
4958 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4959 """Number of bits in binary representation of the positive integer n,
4960 or 0 if n == 0.
4961 """
4962 if n < 0:
4963 raise ValueError("The argument to _nbits should be nonnegative.")
4964 hex_n = "%x" % n
4965 return 4*len(hex_n) - correction[hex_n[0]]
4966
4967def _sqrt_nearest(n, a):
4968 """Closest integer to the square root of the positive integer n. a is
4969 an initial approximation to the square root. Any positive integer
4970 will do for a, but the closer a is to the square root of n the
4971 faster convergence will be.
4972
4973 """
4974 if n <= 0 or a <= 0:
4975 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4976
4977 b=0
4978 while a != b:
4979 b, a = a, a--n//a>>1
4980 return a
4981
4982def _rshift_nearest(x, shift):
4983 """Given an integer x and a nonnegative integer shift, return closest
4984 integer to x / 2**shift; use round-to-even in case of a tie.
4985
4986 """
4987 b, q = 1L << shift, x >> shift
4988 return q + (2*(x & (b-1)) + (q&1) > b)
4989
4990def _div_nearest(a, b):
4991 """Closest integer to a/b, a and b positive integers; rounds to even
4992 in the case of a tie.
4993
4994 """
4995 q, r = divmod(a, b)
4996 return q + (2*r + (q&1) > b)
4997
4998def _ilog(x, M, L = 8):
4999 """Integer approximation to M*log(x/M), with absolute error boundable
5000 in terms only of x/M.
5001
5002 Given positive integers x and M, return an integer approximation to
5003 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5004 between the approximation and the exact result is at most 22. For
5005 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5006 both cases these are upper bounds on the error; it will usually be
5007 much smaller."""
5008
5009 # The basic algorithm is the following: let log1p be the function
5010 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5011 # the reduction
5012 #
5013 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5014 #
5015 # repeatedly until the argument to log1p is small (< 2**-L in
5016 # absolute value). For small y we can use the Taylor series
5017 # expansion
5018 #
5019 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5020 #
5021 # truncating at T such that y**T is small enough. The whole
5022 # computation is carried out in a form of fixed-point arithmetic,
5023 # with a real number z being represented by an integer
5024 # approximation to z*M. To avoid loss of precision, the y below
5025 # is actually an integer approximation to 2**R*y*M, where R is the
5026 # number of reductions performed so far.
5027
5028 y = x-M
5029 # argument reduction; R = number of reductions performed
5030 R = 0
5031 while (R <= L and long(abs(y)) << L-R >= M or
5032 R > L and abs(y) >> R-L >= M):
5033 y = _div_nearest(long(M*y) << 1,
5034 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5035 R += 1
5036
5037 # Taylor series with T terms
5038 T = -int(-10*len(str(M))//(3*L))
5039 yshift = _rshift_nearest(y, R)
5040 w = _div_nearest(M, T)
5041 for k in xrange(T-1, 0, -1):
5042 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5043
5044 return _div_nearest(w*y, M)
5045
5046def _dlog10(c, e, p):
5047 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5048 approximation to 10**p * log10(c*10**e), with an absolute error of
5049 at most 1. Assumes that c*10**e is not exactly 1."""
5050
5051 # increase precision by 2; compensate for this by dividing
5052 # final result by 100
5053 p += 2
5054
5055 # write c*10**e as d*10**f with either:
5056 # f >= 0 and 1 <= d <= 10, or
5057 # f <= 0 and 0.1 <= d <= 1.
5058 # Thus for c*10**e close to 1, f = 0
5059 l = len(str(c))
5060 f = e+l - (e+l >= 1)
5061
5062 if p > 0:
5063 M = 10**p
5064 k = e+p-f
5065 if k >= 0:
5066 c *= 10**k
5067 else:
5068 c = _div_nearest(c, 10**-k)
5069
5070 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005071 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005072 log_d = _div_nearest(log_d*M, log_10)
5073 log_tenpower = f*M # exact
5074 else:
5075 log_d = 0 # error < 2.31
Neal Norwitz18aa3882008-08-24 05:04:52 +00005076 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
Facundo Batista353750c2007-09-13 18:13:15 +00005077
5078 return _div_nearest(log_tenpower+log_d, 100)
5079
5080def _dlog(c, e, p):
5081 """Given integers c, e and p with c > 0, compute an integer
5082 approximation to 10**p * log(c*10**e), with an absolute error of
5083 at most 1. Assumes that c*10**e is not exactly 1."""
5084
5085 # Increase precision by 2. The precision increase is compensated
5086 # for at the end with a division by 100.
5087 p += 2
5088
5089 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5090 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5091 # as 10**p * log(d) + 10**p*f * log(10).
5092 l = len(str(c))
5093 f = e+l - (e+l >= 1)
5094
5095 # compute approximation to 10**p*log(d), with error < 27
5096 if p > 0:
5097 k = e+p-f
5098 if k >= 0:
5099 c *= 10**k
5100 else:
5101 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5102
5103 # _ilog magnifies existing error in c by a factor of at most 10
5104 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5105 else:
5106 # p <= 0: just approximate the whole thing by 0; error < 2.31
5107 log_d = 0
5108
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005109 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005110 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005111 extra = len(str(abs(f)))-1
5112 if p + extra >= 0:
5113 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5114 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5115 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005116 else:
5117 f_log_ten = 0
5118 else:
5119 f_log_ten = 0
5120
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005121 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005122 return _div_nearest(f_log_ten + log_d, 100)
5123
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005124class _Log10Memoize(object):
5125 """Class to compute, store, and allow retrieval of, digits of the
5126 constant log(10) = 2.302585.... This constant is needed by
5127 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5128 def __init__(self):
5129 self.digits = "23025850929940456840179914546843642076011014886"
5130
5131 def getdigits(self, p):
5132 """Given an integer p >= 0, return floor(10**p)*log(10).
5133
5134 For example, self.getdigits(3) returns 2302.
5135 """
5136 # digits are stored as a string, for quick conversion to
5137 # integer in the case that we've already computed enough
5138 # digits; the stored digits should always be correct
5139 # (truncated, not rounded to nearest).
5140 if p < 0:
5141 raise ValueError("p should be nonnegative")
5142
5143 if p >= len(self.digits):
5144 # compute p+3, p+6, p+9, ... digits; continue until at
5145 # least one of the extra digits is nonzero
5146 extra = 3
5147 while True:
5148 # compute p+extra digits, correct to within 1ulp
5149 M = 10**(p+extra+2)
5150 digits = str(_div_nearest(_ilog(10*M, M), 100))
5151 if digits[-extra:] != '0'*extra:
5152 break
5153 extra += 3
5154 # keep all reliable digits so far; remove trailing zeros
5155 # and next nonzero digit
5156 self.digits = digits.rstrip('0')[:-1]
5157 return int(self.digits[:p+1])
5158
5159_log10_digits = _Log10Memoize().getdigits
5160
Facundo Batista353750c2007-09-13 18:13:15 +00005161def _iexp(x, M, L=8):
5162 """Given integers x and M, M > 0, such that x/M is small in absolute
5163 value, compute an integer approximation to M*exp(x/M). For 0 <=
5164 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5165 is usually much smaller)."""
5166
5167 # Algorithm: to compute exp(z) for a real number z, first divide z
5168 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5169 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5170 # series
5171 #
5172 # expm1(x) = x + x**2/2! + x**3/3! + ...
5173 #
5174 # Now use the identity
5175 #
5176 # expm1(2x) = expm1(x)*(expm1(x)+2)
5177 #
5178 # R times to compute the sequence expm1(z/2**R),
5179 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5180
5181 # Find R such that x/2**R/M <= 2**-L
5182 R = _nbits((long(x)<<L)//M)
5183
5184 # Taylor series. (2**L)**T > M
5185 T = -int(-10*len(str(M))//(3*L))
5186 y = _div_nearest(x, T)
5187 Mshift = long(M)<<R
5188 for i in xrange(T-1, 0, -1):
5189 y = _div_nearest(x*(Mshift + y), Mshift * i)
5190
5191 # Expansion
5192 for k in xrange(R-1, -1, -1):
5193 Mshift = long(M)<<(k+2)
5194 y = _div_nearest(y*(y+Mshift), Mshift)
5195
5196 return M+y
5197
5198def _dexp(c, e, p):
5199 """Compute an approximation to exp(c*10**e), with p decimal places of
5200 precision.
5201
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005202 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005203
5204 10**(p-1) <= d <= 10**p, and
5205 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5206
5207 In other words, d*10**f is an approximation to exp(c*10**e) with p
5208 digits of precision, and with an error in d of at most 1. This is
5209 almost, but not quite, the same as the error being < 1ulp: when d
5210 = 10**(p-1) the error could be up to 10 ulp."""
5211
5212 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5213 p += 2
5214
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005215 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005216 extra = max(0, e + len(str(c)) - 1)
5217 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005218
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005219 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005220 # rounding down
5221 shift = e+q
5222 if shift >= 0:
5223 cshift = c*10**shift
5224 else:
5225 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005226 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005227
5228 # reduce remainder back to original precision
5229 rem = _div_nearest(rem, 10**extra)
5230
5231 # error in result of _iexp < 120; error after division < 0.62
5232 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5233
5234def _dpower(xc, xe, yc, ye, p):
5235 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5236 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5237
5238 10**(p-1) <= c <= 10**p, and
5239 (c-1)*10**e < x**y < (c+1)*10**e
5240
5241 in other words, c*10**e is an approximation to x**y with p digits
5242 of precision, and with an error in c of at most 1. (This is
5243 almost, but not quite, the same as the error being < 1ulp: when c
5244 == 10**(p-1) we can only guarantee error < 10ulp.)
5245
5246 We assume that: x is positive and not equal to 1, and y is nonzero.
5247 """
5248
5249 # Find b such that 10**(b-1) <= |y| <= 10**b
5250 b = len(str(abs(yc))) + ye
5251
5252 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5253 lxc = _dlog(xc, xe, p+b+1)
5254
5255 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5256 shift = ye-b
5257 if shift >= 0:
5258 pc = lxc*yc*10**shift
5259 else:
5260 pc = _div_nearest(lxc*yc, 10**-shift)
5261
5262 if pc == 0:
5263 # we prefer a result that isn't exactly 1; this makes it
5264 # easier to compute a correctly rounded result in __pow__
5265 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5266 coeff, exp = 10**(p-1)+1, 1-p
5267 else:
5268 coeff, exp = 10**p-1, -p
5269 else:
5270 coeff, exp = _dexp(pc, -(p+1), p+1)
5271 coeff = _div_nearest(coeff, 10)
5272 exp += 1
5273
5274 return coeff, exp
5275
5276def _log10_lb(c, correction = {
5277 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5278 '6': 23, '7': 16, '8': 10, '9': 5}):
5279 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5280 if c <= 0:
5281 raise ValueError("The argument to _log10_lb should be nonnegative.")
5282 str_c = str(c)
5283 return 100*len(str_c) - correction[str_c[0]]
5284
Facundo Batista59c58842007-04-10 12:58:45 +00005285##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005286
Facundo Batista353750c2007-09-13 18:13:15 +00005287def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005288 """Convert other to Decimal.
5289
5290 Verifies that it's ok to use in an implicit construction.
5291 """
5292 if isinstance(other, Decimal):
5293 return other
5294 if isinstance(other, (int, long)):
5295 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005296 if raiseit:
5297 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005298 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005299
Facundo Batista59c58842007-04-10 12:58:45 +00005300##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005301
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005302# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005303# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005304
5305DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005306 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005307 traps=[DivisionByZero, Overflow, InvalidOperation],
5308 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005309 Emax=999999999,
5310 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005311 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005312)
5313
5314# Pre-made alternate contexts offered by the specification
5315# Don't change these; the user should be able to select these
5316# contexts and be able to reproduce results from other implementations
5317# of the spec.
5318
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005319BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005320 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005321 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5322 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323)
5324
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005325ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005326 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005327 traps=[],
5328 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005329)
5330
5331
Facundo Batista72bc54f2007-11-23 17:59:00 +00005332##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005333#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005334# Regular expression used for parsing numeric strings. Additional
5335# comments:
5336#
5337# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5338# whitespace. But note that the specification disallows whitespace in
5339# a numeric string.
5340#
5341# 2. For finite numbers (not infinities and NaNs) the body of the
5342# number between the optional sign and the optional exponent must have
5343# at least one decimal digit, possibly after the decimal point. The
5344# lookahead expression '(?=\d|\.\d)' checks this.
5345#
5346# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5347# other meaning for \d than the numbers [0-9].
5348
5349import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005350_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005351# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005352 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005353 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005354 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5355 (?P<int>[0-9]*) # having a (possibly empty) integer part
5356 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5357 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005358 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005359 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005360 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005361 (?P<signal>s)? # ...an (optionally signaling)
5362 NaN # NaN
5363 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005364 )
5365# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005366 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005367""", re.VERBOSE | re.IGNORECASE).match
5368
Facundo Batista2ec74152007-12-03 17:55:00 +00005369_all_zeros = re.compile('0*$').match
5370_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005371
5372##### PEP3101 support functions ##############################################
5373# The functions parse_format_specifier and format_align have little to do
5374# with the Decimal class, and could potentially be reused for other pure
5375# Python numeric classes that want to implement __format__
5376#
5377# A format specifier for Decimal looks like:
5378#
5379# [[fill]align][sign][0][minimumwidth][.precision][type]
5380#
5381
5382_parse_format_specifier_regex = re.compile(r"""\A
5383(?:
5384 (?P<fill>.)?
5385 (?P<align>[<>=^])
5386)?
5387(?P<sign>[-+ ])?
5388(?P<zeropad>0)?
5389(?P<minimumwidth>(?!0)\d+)?
5390(?:\.(?P<precision>0|(?!0)\d+))?
5391(?P<type>[eEfFgG%])?
5392\Z
5393""", re.VERBOSE)
5394
Facundo Batista72bc54f2007-11-23 17:59:00 +00005395del re
5396
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005397def _parse_format_specifier(format_spec):
5398 """Parse and validate a format specifier.
5399
5400 Turns a standard numeric format specifier into a dict, with the
5401 following entries:
5402
5403 fill: fill character to pad field to minimum width
5404 align: alignment type, either '<', '>', '=' or '^'
5405 sign: either '+', '-' or ' '
5406 minimumwidth: nonnegative integer giving minimum width
5407 precision: nonnegative integer giving precision, or None
5408 type: one of the characters 'eEfFgG%', or None
5409 unicode: either True or False (always True for Python 3.x)
5410
5411 """
5412 m = _parse_format_specifier_regex.match(format_spec)
5413 if m is None:
5414 raise ValueError("Invalid format specifier: " + format_spec)
5415
5416 # get the dictionary
5417 format_dict = m.groupdict()
5418
5419 # defaults for fill and alignment
5420 fill = format_dict['fill']
5421 align = format_dict['align']
5422 if format_dict.pop('zeropad') is not None:
5423 # in the face of conflict, refuse the temptation to guess
5424 if fill is not None and fill != '0':
5425 raise ValueError("Fill character conflicts with '0'"
5426 " in format specifier: " + format_spec)
5427 if align is not None and align != '=':
5428 raise ValueError("Alignment conflicts with '0' in "
5429 "format specifier: " + format_spec)
5430 fill = '0'
5431 align = '='
5432 format_dict['fill'] = fill or ' '
5433 format_dict['align'] = align or '<'
5434
5435 if format_dict['sign'] is None:
5436 format_dict['sign'] = '-'
5437
5438 # turn minimumwidth and precision entries into integers.
5439 # minimumwidth defaults to 0; precision remains None if not given
5440 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5441 if format_dict['precision'] is not None:
5442 format_dict['precision'] = int(format_dict['precision'])
5443
5444 # if format type is 'g' or 'G' then a precision of 0 makes little
5445 # sense; convert it to 1. Same if format type is unspecified.
5446 if format_dict['precision'] == 0:
5447 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5448 format_dict['precision'] = 1
5449
5450 # record whether return type should be str or unicode
5451 format_dict['unicode'] = isinstance(format_spec, unicode)
5452
5453 return format_dict
5454
5455def _format_align(body, spec_dict):
5456 """Given an unpadded, non-aligned numeric string, add padding and
5457 aligment to conform with the given format specifier dictionary (as
5458 output from parse_format_specifier).
5459
5460 It's assumed that if body is negative then it starts with '-'.
5461 Any leading sign ('-' or '+') is stripped from the body before
5462 applying the alignment and padding rules, and replaced in the
5463 appropriate position.
5464
5465 """
5466 # figure out the sign; we only examine the first character, so if
5467 # body has leading whitespace the results may be surprising.
5468 if len(body) > 0 and body[0] in '-+':
5469 sign = body[0]
5470 body = body[1:]
5471 else:
5472 sign = ''
5473
5474 if sign != '-':
5475 if spec_dict['sign'] in ' +':
5476 sign = spec_dict['sign']
5477 else:
5478 sign = ''
5479
5480 # how much extra space do we have to play with?
5481 minimumwidth = spec_dict['minimumwidth']
5482 fill = spec_dict['fill']
5483 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5484
5485 align = spec_dict['align']
5486 if align == '<':
5487 result = padding + sign + body
5488 elif align == '>':
5489 result = sign + body + padding
5490 elif align == '=':
5491 result = sign + padding + body
5492 else: #align == '^'
5493 half = len(padding)//2
5494 result = padding[:half] + sign + body + padding[half:]
5495
5496 # make sure that result is unicode if necessary
5497 if spec_dict['unicode']:
5498 result = unicode(result)
5499
5500 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005501
Facundo Batista59c58842007-04-10 12:58:45 +00005502##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005503
Facundo Batista59c58842007-04-10 12:58:45 +00005504# Reusable defaults
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005505_Infinity = Decimal('Inf')
5506_NegativeInfinity = Decimal('-Inf')
Mark Dickinsonfd6032d2009-01-02 23:16:51 +00005507_NaN = Decimal('NaN')
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005508_Zero = Decimal(0)
5509_One = Decimal(1)
5510_NegativeOne = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005511
Mark Dickinsone4d46b22009-01-03 12:09:22 +00005512# _SignedInfinity[sign] is infinity w/ that sign
5513_SignedInfinity = (_Infinity, _NegativeInfinity)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005514
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005515
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005516
5517if __name__ == '__main__':
5518 import doctest, sys
5519 doctest.testmod(sys.modules[__name__])