blob: 5d25012bd0722966cb29d908fe3e07d0136e1753 [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)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000219 return NaN
220
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):
Facundo Batista353750c2007-09-13 18:13:15 +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):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000245 return Infsign[sign]
246
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):
Facundo Batistacce8df22007-09-18 16:53:18 +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):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000267 return NaN
268
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):
293 return NaN
294
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):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000343 return Infsign[sign]
344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
346 return Infsign[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:
351 return Infsign[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
480 """
Neal Norwitz681d8672006-09-02 18:51:34 +0000481 # The string below can't be included in the docstring until Python 2.6
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000482 # as the doctest module doesn't understand __future__ statements
483 """
484 >>> from __future__ import with_statement
485 >>> print getcontext().prec
486 28
487 >>> with localcontext():
488 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000489 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000490 ... print ctx.prec
491 ...
492 30
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
495 ...
496 9
497 >>> print getcontext().prec
498 28
499 """
Nick Coghlanced12182006-09-02 03:54:17 +0000500 if ctx is None: ctx = getcontext()
501 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000503
Facundo Batista59c58842007-04-10 12:58:45 +0000504##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000505
506class Decimal(object):
507 """Floating point class for decimal arithmetic."""
508
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000513
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000514 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000515 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000516 """Create a decimal point instance.
517
518 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000522 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000525 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000527 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000528 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000529
Facundo Batista72bc54f2007-11-23 17:59:00 +0000530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
537
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000538 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000539
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000543 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000549
Facundo Batista0d157a02007-11-30 17:15:25 +0000550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
557 fracpart = m.group('frac')
558 exp = int(m.group('exp') or '0')
559 if fracpart is not None:
560 self._int = (intpart+fracpart).lstrip('0') or '0'
561 self._exp = exp - len(fracpart)
562 else:
563 self._int = intpart.lstrip('0') or '0'
564 self._exp = exp
565 self._is_special = False
566 else:
567 diag = m.group('diag')
568 if diag is not None:
569 # NaN
570 self._int = diag.lstrip('0')
571 if m.group('signal'):
572 self._exp = 'N'
573 else:
574 self._exp = 'n'
575 else:
576 # infinity
577 self._int = '0'
578 self._exp = 'F'
579 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 return self
581
582 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000583 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000584 if value >= 0:
585 self._sign = 0
586 else:
587 self._sign = 1
588 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000589 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000590 self._is_special = False
591 return self
592
593 # From another decimal
594 if isinstance(value, Decimal):
595 self._exp = value._exp
596 self._sign = value._sign
597 self._int = value._int
598 self._is_special = value._is_special
599 return self
600
601 # From an internal working value
602 if isinstance(value, _WorkRep):
603 self._sign = value.sign
604 self._int = str(value.int)
605 self._exp = int(value.exp)
606 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000607 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000608
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value, (list,tuple)):
611 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000621 if value[2] == 'F':
622 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000623 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000624 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000625 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000626 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000627 # process and validate the digits in value[1]
628 digits = []
629 for digit in value[1]:
630 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
631 # skip leading zeros
632 if digits or digit != 0:
633 digits.append(digit)
634 else:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
637 "0 through 9.")
638 if value[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000640 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000641 self._exp = value[2]
642 self._is_special = True
643 elif isinstance(value[2], (int, long)):
644 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000645 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000646 self._exp = value[2]
647 self._is_special = False
648 else:
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000652 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000653
Raymond Hettingerbf440692004-07-10 14:14:37 +0000654 if isinstance(value, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
657
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000658 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000659
660 def _isnan(self):
661 """Returns whether the number is not actually one.
662
663 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000664 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000665 2 if sNaN
666 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000667 if self._is_special:
668 exp = self._exp
669 if exp == 'n':
670 return 1
671 elif exp == 'N':
672 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000673 return 0
674
675 def _isinfinity(self):
676 """Returns whether the number is infinite
677
678 0 if finite or not a number
679 1 if +INF
680 -1 if -INF
681 """
682 if self._exp == 'F':
683 if self._sign:
684 return -1
685 return 1
686 return 0
687
Facundo Batista353750c2007-09-13 18:13:15 +0000688 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000689 """Returns whether the number is not actually one.
690
691 if self, other are sNaN, signal
692 if self, other are NaN return nan
693 return 0
694
695 Done before operations.
696 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000697
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000698 self_is_nan = self._isnan()
699 if other is None:
700 other_is_nan = False
701 else:
702 other_is_nan = other._isnan()
703
704 if self_is_nan or other_is_nan:
705 if context is None:
706 context = getcontext()
707
708 if self_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000710 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000711 if other_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000713 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000714 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000715 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000716
Facundo Batista353750c2007-09-13 18:13:15 +0000717 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000718 return 0
719
Mark Dickinson2fc92632008-02-06 22:10:50 +0000720 def _compare_check_nans(self, other, context):
721 """Version of _check_nans used for the signaling comparisons
722 compare_signal, __le__, __lt__, __ge__, __gt__.
723
724 Signal InvalidOperation if either self or other is a (quiet
725 or signaling) NaN. Signaling NaNs take precedence over quiet
726 NaNs.
727
728 Return 0 if neither operand is a NaN.
729
730 """
731 if context is None:
732 context = getcontext()
733
734 if self._is_special or other._is_special:
735 if self.is_snan():
736 return context._raise_error(InvalidOperation,
737 'comparison involving sNaN',
738 self)
739 elif other.is_snan():
740 return context._raise_error(InvalidOperation,
741 'comparison involving sNaN',
742 other)
743 elif self.is_qnan():
744 return context._raise_error(InvalidOperation,
745 'comparison involving NaN',
746 self)
747 elif other.is_qnan():
748 return context._raise_error(InvalidOperation,
749 'comparison involving NaN',
750 other)
751 return 0
752
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000754 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755
Facundo Batista1a191df2007-10-02 17:01:24 +0000756 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000757 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000758 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000759
Mark Dickinson2fc92632008-02-06 22:10:50 +0000760 def _cmp(self, other):
761 """Compare the two non-NaN decimal instances self and other.
762
763 Returns -1 if self < other, 0 if self == other and 1
764 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000765
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000766 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000767 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000768
Facundo Batista353750c2007-09-13 18:13:15 +0000769 # check for zeros; note that cmp(0, -0) should return 0
770 if not self:
771 if not other:
772 return 0
773 else:
774 return -((-1)**other._sign)
775 if not other:
776 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000777
Facundo Batista59c58842007-04-10 12:58:45 +0000778 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000779 if other._sign < self._sign:
780 return -1
781 if self._sign < other._sign:
782 return 1
783
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000784 self_adjusted = self.adjusted()
785 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000786 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000787 self_padded = self._int + '0'*(self._exp - other._exp)
788 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000789 return cmp(self_padded, other_padded) * (-1)**self._sign
790 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000791 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000792 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000793 return -((-1)**self._sign)
794
Mark Dickinson2fc92632008-02-06 22:10:50 +0000795 # Note: The Decimal standard doesn't cover rich comparisons for
796 # Decimals. In particular, the specification is silent on the
797 # subject of what should happen for a comparison involving a NaN.
798 # We take the following approach:
799 #
800 # == comparisons involving a NaN always return False
801 # != comparisons involving a NaN always return True
802 # <, >, <= and >= comparisons involving a (quiet or signaling)
803 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000804 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000805 #
806 # This behavior is designed to conform as closely as possible to
807 # that specified by IEEE 754.
808
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000809 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000810 other = _convert_other(other)
811 if other is NotImplemented:
812 return other
813 if self.is_nan() or other.is_nan():
814 return False
815 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000816
817 def __ne__(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 True
823 return self._cmp(other) != 0
824
825 def __lt__(self, other, context=None):
826 other = _convert_other(other)
827 if other is NotImplemented:
828 return other
829 ans = self._compare_check_nans(other, context)
830 if ans:
831 return False
832 return self._cmp(other) < 0
833
834 def __le__(self, other, context=None):
835 other = _convert_other(other)
836 if other is NotImplemented:
837 return other
838 ans = self._compare_check_nans(other, context)
839 if ans:
840 return False
841 return self._cmp(other) <= 0
842
843 def __gt__(self, other, context=None):
844 other = _convert_other(other)
845 if other is NotImplemented:
846 return other
847 ans = self._compare_check_nans(other, context)
848 if ans:
849 return False
850 return self._cmp(other) > 0
851
852 def __ge__(self, other, context=None):
853 other = _convert_other(other)
854 if other is NotImplemented:
855 return other
856 ans = self._compare_check_nans(other, context)
857 if ans:
858 return False
859 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000860
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000861 def compare(self, other, context=None):
862 """Compares one to another.
863
864 -1 => a < b
865 0 => a = b
866 1 => a > b
867 NaN => one is NaN
868 Like __cmp__, but returns Decimal instances.
869 """
Facundo Batista353750c2007-09-13 18:13:15 +0000870 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000871
Facundo Batista59c58842007-04-10 12:58:45 +0000872 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000873 if (self._is_special or other and other._is_special):
874 ans = self._check_nans(other, context)
875 if ans:
876 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000877
Mark Dickinson2fc92632008-02-06 22:10:50 +0000878 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000879
880 def __hash__(self):
881 """x.__hash__() <==> hash(x)"""
882 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000883 #
884 # The hash of a nonspecial noninteger Decimal must depend only
885 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000886 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000887 if self._is_special:
888 if self._isnan():
889 raise TypeError('Cannot hash a NaN value.')
890 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000891 if not self:
892 return 0
893 if self._isinteger():
894 op = _WorkRep(self.to_integral_value())
895 # to make computation feasible for Decimals with large
896 # exponent, we use the fact that hash(n) == hash(m) for
897 # any two nonzero integers n and m such that (i) n and m
898 # have the same sign, and (ii) n is congruent to m modulo
899 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
900 # hash((-1)**s*c*pow(10, e, 2**64-1).
901 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000902 # The value of a nonzero nonspecial Decimal instance is
903 # faithfully represented by the triple consisting of its sign,
904 # its adjusted exponent, and its coefficient with trailing
905 # zeros removed.
906 return hash((self._sign,
907 self._exp+len(self._int),
908 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000909
910 def as_tuple(self):
911 """Represents the number as a triple tuple.
912
913 To show the internals exactly as they are.
914 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000915 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000916
917 def __repr__(self):
918 """Represents the number as an instance of Decimal."""
919 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000920 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000921
Facundo Batista353750c2007-09-13 18:13:15 +0000922 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000923 """Return string representation of the number in scientific notation.
924
925 Captures all of the information in the underlying representation.
926 """
927
Facundo Batista62edb712007-12-03 16:29:52 +0000928 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000929 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000930 if self._exp == 'F':
931 return sign + 'Infinity'
932 elif self._exp == 'n':
933 return sign + 'NaN' + self._int
934 else: # self._exp == 'N'
935 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000936
Facundo Batista62edb712007-12-03 16:29:52 +0000937 # number of digits of self._int to left of decimal point
938 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000939
Facundo Batista62edb712007-12-03 16:29:52 +0000940 # dotplace is number of digits of self._int to the left of the
941 # decimal point in the mantissa of the output string (that is,
942 # after adjusting the exponent)
943 if self._exp <= 0 and leftdigits > -6:
944 # no exponent required
945 dotplace = leftdigits
946 elif not eng:
947 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000949 elif self._int == '0':
950 # engineering notation, zero
951 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000952 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000953 # engineering notation, nonzero
954 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000955
Facundo Batista62edb712007-12-03 16:29:52 +0000956 if dotplace <= 0:
957 intpart = '0'
958 fracpart = '.' + '0'*(-dotplace) + self._int
959 elif dotplace >= len(self._int):
960 intpart = self._int+'0'*(dotplace-len(self._int))
961 fracpart = ''
962 else:
963 intpart = self._int[:dotplace]
964 fracpart = '.' + self._int[dotplace:]
965 if leftdigits == dotplace:
966 exp = ''
967 else:
968 if context is None:
969 context = getcontext()
970 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
971
972 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000973
974 def to_eng_string(self, context=None):
975 """Convert to engineering-type string.
976
977 Engineering notation has an exponent which is a multiple of 3, so there
978 are up to 3 digits left of the decimal place.
979
980 Same rules for when in exponential and when as a value as in __str__.
981 """
Facundo Batista353750c2007-09-13 18:13:15 +0000982 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000983
984 def __neg__(self, context=None):
985 """Returns a copy with the sign switched.
986
987 Rounds, if it has reason.
988 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000989 if self._is_special:
990 ans = self._check_nans(context=context)
991 if ans:
992 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993
994 if not self:
995 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000996 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000997 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000998 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000999
1000 if context is None:
1001 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001002 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001003
1004 def __pos__(self, context=None):
1005 """Returns a copy, unless it is a sNaN.
1006
1007 Rounds the number (if more then precision digits)
1008 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001009 if self._is_special:
1010 ans = self._check_nans(context=context)
1011 if ans:
1012 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001013
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001014 if not self:
1015 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001016 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001017 else:
1018 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001020 if context is None:
1021 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001022 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001023
Facundo Batistae64acfa2007-12-17 14:18:42 +00001024 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001025 """Returns the absolute value of self.
1026
Facundo Batistae64acfa2007-12-17 14:18:42 +00001027 If the keyword argument 'round' is false, do not round. The
1028 expression self.__abs__(round=False) is equivalent to
1029 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001030 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001031 if not round:
1032 return self.copy_abs()
1033
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001034 if self._is_special:
1035 ans = self._check_nans(context=context)
1036 if ans:
1037 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001038
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001039 if self._sign:
1040 ans = self.__neg__(context=context)
1041 else:
1042 ans = self.__pos__(context=context)
1043
1044 return ans
1045
1046 def __add__(self, other, context=None):
1047 """Returns self + other.
1048
1049 -INF + INF (or the reverse) cause InvalidOperation errors.
1050 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001051 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001052 if other is NotImplemented:
1053 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001055 if context is None:
1056 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001057
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001058 if self._is_special or other._is_special:
1059 ans = self._check_nans(other, context)
1060 if ans:
1061 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001062
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001063 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001064 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001065 if self._sign != other._sign and other._isinfinity():
1066 return context._raise_error(InvalidOperation, '-INF + INF')
1067 return Decimal(self)
1068 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001069 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001070
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 exp = min(self._exp, other._exp)
1072 negativezero = 0
1073 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001074 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001075 negativezero = 1
1076
1077 if not self and not other:
1078 sign = min(self._sign, other._sign)
1079 if negativezero:
1080 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001081 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001082 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001083 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001085 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001086 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001087 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001088 return ans
1089 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001090 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001091 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001092 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001093 return ans
1094
1095 op1 = _WorkRep(self)
1096 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001097 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001098
1099 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001100 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001101 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001102 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001103 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001104 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001105 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001106 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001108 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001109 if op1.sign == 1:
1110 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001111 op1.sign, op2.sign = op2.sign, op1.sign
1112 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001113 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001114 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001115 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001116 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001117 op1.sign, op2.sign = (0, 0)
1118 else:
1119 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001120 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001121
Raymond Hettinger17931de2004-10-27 06:21:46 +00001122 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001123 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001124 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001125 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126
1127 result.exp = op1.exp
1128 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001129 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001130 return ans
1131
1132 __radd__ = __add__
1133
1134 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001135 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001137 if other is NotImplemented:
1138 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001139
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001140 if self._is_special or other._is_special:
1141 ans = self._check_nans(other, context=context)
1142 if ans:
1143 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001144
Facundo Batista353750c2007-09-13 18:13:15 +00001145 # self - other is computed as self + other.copy_negate()
1146 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001147
1148 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001149 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001150 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001151 if other is NotImplemented:
1152 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001153
Facundo Batista353750c2007-09-13 18:13:15 +00001154 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001155
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001156 def __mul__(self, other, context=None):
1157 """Return self * other.
1158
1159 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1160 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001161 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001162 if other is NotImplemented:
1163 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001164
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165 if context is None:
1166 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001167
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001168 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001169
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001170 if self._is_special or other._is_special:
1171 ans = self._check_nans(other, context)
1172 if ans:
1173 return ans
1174
1175 if self._isinfinity():
1176 if not other:
1177 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1178 return Infsign[resultsign]
1179
1180 if other._isinfinity():
1181 if not self:
1182 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1183 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001184
1185 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001186
1187 # Special case for multiplying by zero
1188 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001189 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001190 # Fixing in case the exponent is out of bounds
1191 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001192 return ans
1193
1194 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001195 if self._int == '1':
1196 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001197 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001199 if other._int == '1':
1200 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001201 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202 return ans
1203
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001204 op1 = _WorkRep(self)
1205 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001206
Facundo Batista72bc54f2007-11-23 17:59:00 +00001207 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001208 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001209
1210 return ans
1211 __rmul__ = __mul__
1212
1213 def __div__(self, other, context=None):
1214 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001215 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001216 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001217 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001218
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001219 if context is None:
1220 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001221
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001222 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223
1224 if self._is_special or other._is_special:
1225 ans = self._check_nans(other, context)
1226 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001227 return ans
1228
1229 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001230 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001231
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001232 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001233 return Infsign[sign]
1234
1235 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001237 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001238
1239 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001240 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001241 if not self:
1242 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001243 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001244
Facundo Batistacce8df22007-09-18 16:53:18 +00001245 if not self:
1246 exp = self._exp - other._exp
1247 coeff = 0
1248 else:
1249 # OK, so neither = 0, INF or NaN
1250 shift = len(other._int) - len(self._int) + context.prec + 1
1251 exp = self._exp - other._exp - shift
1252 op1 = _WorkRep(self)
1253 op2 = _WorkRep(other)
1254 if shift >= 0:
1255 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1256 else:
1257 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1258 if remainder:
1259 # result is not exact; adjust to ensure correct rounding
1260 if coeff % 5 == 0:
1261 coeff += 1
1262 else:
1263 # result is exact; get as close to ideal exponent as possible
1264 ideal_exp = self._exp - other._exp
1265 while exp < ideal_exp and coeff % 10 == 0:
1266 coeff //= 10
1267 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001268
Facundo Batista72bc54f2007-11-23 17:59:00 +00001269 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001270 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001271
Facundo Batistacce8df22007-09-18 16:53:18 +00001272 __truediv__ = __div__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001273
Facundo Batistacce8df22007-09-18 16:53:18 +00001274 def _divide(self, other, context):
1275 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001276
Facundo Batistacce8df22007-09-18 16:53:18 +00001277 Assumes that neither self nor other is a NaN, that self is not
1278 infinite and that other is nonzero.
1279 """
1280 sign = self._sign ^ other._sign
1281 if other._isinfinity():
1282 ideal_exp = self._exp
1283 else:
1284 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001285
Facundo Batistacce8df22007-09-18 16:53:18 +00001286 expdiff = self.adjusted() - other.adjusted()
1287 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001288 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001289 self._rescale(ideal_exp, context.rounding))
1290 if expdiff <= context.prec:
1291 op1 = _WorkRep(self)
1292 op2 = _WorkRep(other)
1293 if op1.exp >= op2.exp:
1294 op1.int *= 10**(op1.exp - op2.exp)
1295 else:
1296 op2.int *= 10**(op2.exp - op1.exp)
1297 q, r = divmod(op1.int, op2.int)
1298 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001299 return (_dec_from_triple(sign, str(q), 0),
1300 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001301
Facundo Batistacce8df22007-09-18 16:53:18 +00001302 # Here the quotient is too large to be representable
1303 ans = context._raise_error(DivisionImpossible,
1304 'quotient too large in //, % or divmod')
1305 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001306
1307 def __rdiv__(self, other, context=None):
1308 """Swaps self/other and returns __div__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001309 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001310 if other is NotImplemented:
1311 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001312 return other.__div__(self, context=context)
1313 __rtruediv__ = __rdiv__
1314
1315 def __divmod__(self, other, context=None):
1316 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001317 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001318 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001319 other = _convert_other(other)
1320 if other is NotImplemented:
1321 return other
1322
1323 if context is None:
1324 context = getcontext()
1325
1326 ans = self._check_nans(other, context)
1327 if ans:
1328 return (ans, ans)
1329
1330 sign = self._sign ^ other._sign
1331 if self._isinfinity():
1332 if other._isinfinity():
1333 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1334 return ans, ans
1335 else:
1336 return (Infsign[sign],
1337 context._raise_error(InvalidOperation, 'INF % x'))
1338
1339 if not other:
1340 if not self:
1341 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1342 return ans, ans
1343 else:
1344 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1345 context._raise_error(InvalidOperation, 'x % 0'))
1346
1347 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001348 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001349 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001350
1351 def __rdivmod__(self, other, context=None):
1352 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001353 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001354 if other is NotImplemented:
1355 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001356 return other.__divmod__(self, context=context)
1357
1358 def __mod__(self, other, context=None):
1359 """
1360 self % other
1361 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001362 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001363 if other is NotImplemented:
1364 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001365
Facundo Batistacce8df22007-09-18 16:53:18 +00001366 if context is None:
1367 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
Facundo Batistacce8df22007-09-18 16:53:18 +00001369 ans = self._check_nans(other, context)
1370 if ans:
1371 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001372
Facundo Batistacce8df22007-09-18 16:53:18 +00001373 if self._isinfinity():
1374 return context._raise_error(InvalidOperation, 'INF % x')
1375 elif not other:
1376 if self:
1377 return context._raise_error(InvalidOperation, 'x % 0')
1378 else:
1379 return context._raise_error(DivisionUndefined, '0 % 0')
1380
1381 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001382 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001383 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001384
1385 def __rmod__(self, other, context=None):
1386 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001387 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001388 if other is NotImplemented:
1389 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001390 return other.__mod__(self, context=context)
1391
1392 def remainder_near(self, other, context=None):
1393 """
1394 Remainder nearest to 0- abs(remainder-near) <= other/2
1395 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001396 if context is None:
1397 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001398
Facundo Batista353750c2007-09-13 18:13:15 +00001399 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Facundo Batista353750c2007-09-13 18:13:15 +00001401 ans = self._check_nans(other, context)
1402 if ans:
1403 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001404
Facundo Batista353750c2007-09-13 18:13:15 +00001405 # self == +/-infinity -> InvalidOperation
1406 if self._isinfinity():
1407 return context._raise_error(InvalidOperation,
1408 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001409
Facundo Batista353750c2007-09-13 18:13:15 +00001410 # other == 0 -> either InvalidOperation or DivisionUndefined
1411 if not other:
1412 if self:
1413 return context._raise_error(InvalidOperation,
1414 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001415 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001416 return context._raise_error(DivisionUndefined,
1417 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001418
Facundo Batista353750c2007-09-13 18:13:15 +00001419 # other = +/-infinity -> remainder = self
1420 if other._isinfinity():
1421 ans = Decimal(self)
1422 return ans._fix(context)
1423
1424 # self = 0 -> remainder = self, with ideal exponent
1425 ideal_exponent = min(self._exp, other._exp)
1426 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001427 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001428 return ans._fix(context)
1429
1430 # catch most cases of large or small quotient
1431 expdiff = self.adjusted() - other.adjusted()
1432 if expdiff >= context.prec + 1:
1433 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001434 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001435 if expdiff <= -2:
1436 # expdiff <= -2 => abs(self/other) < 0.1
1437 ans = self._rescale(ideal_exponent, context.rounding)
1438 return ans._fix(context)
1439
1440 # adjust both arguments to have the same exponent, then divide
1441 op1 = _WorkRep(self)
1442 op2 = _WorkRep(other)
1443 if op1.exp >= op2.exp:
1444 op1.int *= 10**(op1.exp - op2.exp)
1445 else:
1446 op2.int *= 10**(op2.exp - op1.exp)
1447 q, r = divmod(op1.int, op2.int)
1448 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1449 # 10**ideal_exponent. Apply correction to ensure that
1450 # abs(remainder) <= abs(other)/2
1451 if 2*r + (q&1) > op2.int:
1452 r -= op2.int
1453 q += 1
1454
1455 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001456 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001457
1458 # result has same sign as self unless r is negative
1459 sign = self._sign
1460 if r < 0:
1461 sign = 1-sign
1462 r = -r
1463
Facundo Batista72bc54f2007-11-23 17:59:00 +00001464 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001465 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001466
1467 def __floordiv__(self, other, context=None):
1468 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001469 other = _convert_other(other)
1470 if other is NotImplemented:
1471 return other
1472
1473 if context is None:
1474 context = getcontext()
1475
1476 ans = self._check_nans(other, context)
1477 if ans:
1478 return ans
1479
1480 if self._isinfinity():
1481 if other._isinfinity():
1482 return context._raise_error(InvalidOperation, 'INF // INF')
1483 else:
1484 return Infsign[self._sign ^ other._sign]
1485
1486 if not other:
1487 if self:
1488 return context._raise_error(DivisionByZero, 'x // 0',
1489 self._sign ^ other._sign)
1490 else:
1491 return context._raise_error(DivisionUndefined, '0 // 0')
1492
1493 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001494
1495 def __rfloordiv__(self, other, context=None):
1496 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001497 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001498 if other is NotImplemented:
1499 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001500 return other.__floordiv__(self, context=context)
1501
1502 def __float__(self):
1503 """Float representation."""
1504 return float(str(self))
1505
1506 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001507 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001508 if self._is_special:
1509 if self._isnan():
1510 context = getcontext()
1511 return context._raise_error(InvalidContext)
1512 elif self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001513 raise OverflowError("Cannot convert infinity to long")
Facundo Batista353750c2007-09-13 18:13:15 +00001514 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001515 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001516 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001517 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001518 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001519
Raymond Hettinger5a053642008-01-24 19:05:29 +00001520 __trunc__ = __int__
1521
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001522 @property
1523 def real(self):
1524 return self
1525
1526 @property
1527 def imag(self):
1528 return Decimal(0)
1529
1530 def conjugate(self):
1531 return self
1532
1533 def __complex__(self):
1534 return complex(float(self))
1535
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001536 def __long__(self):
1537 """Converts to a long.
1538
1539 Equivalent to long(int(self))
1540 """
1541 return long(self.__int__())
1542
Facundo Batista353750c2007-09-13 18:13:15 +00001543 def _fix_nan(self, context):
1544 """Decapitate the payload of a NaN to fit the context"""
1545 payload = self._int
1546
1547 # maximum length of payload is precision if _clamp=0,
1548 # precision-1 if _clamp=1.
1549 max_payload_len = context.prec - context._clamp
1550 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001551 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1552 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001553 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001554
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001555 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001556 """Round if it is necessary to keep self within prec precision.
1557
1558 Rounds and fixes the exponent. Does not raise on a sNaN.
1559
1560 Arguments:
1561 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001562 context - context used.
1563 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001564
Facundo Batista353750c2007-09-13 18:13:15 +00001565 if self._is_special:
1566 if self._isnan():
1567 # decapitate payload if necessary
1568 return self._fix_nan(context)
1569 else:
1570 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001571 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001572
Facundo Batista353750c2007-09-13 18:13:15 +00001573 # if self is zero then exponent should be between Etiny and
1574 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1575 Etiny = context.Etiny()
1576 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001577 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001578 exp_max = [context.Emax, Etop][context._clamp]
1579 new_exp = min(max(self._exp, Etiny), exp_max)
1580 if new_exp != self._exp:
1581 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001582 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001583 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001584 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001585
1586 # exp_min is the smallest allowable exponent of the result,
1587 # equal to max(self.adjusted()-context.prec+1, Etiny)
1588 exp_min = len(self._int) + self._exp - context.prec
1589 if exp_min > Etop:
1590 # overflow: exp_min > Etop iff self.adjusted() > Emax
1591 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001592 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001593 return context._raise_error(Overflow, 'above Emax', self._sign)
1594 self_is_subnormal = exp_min < Etiny
1595 if self_is_subnormal:
1596 context._raise_error(Subnormal)
1597 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001598
Facundo Batista353750c2007-09-13 18:13:15 +00001599 # round if self has too many digits
1600 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001601 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001602 digits = len(self._int) + self._exp - exp_min
1603 if digits < 0:
1604 self = _dec_from_triple(self._sign, '1', exp_min-1)
1605 digits = 0
1606 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1607 changed = this_function(digits)
1608 coeff = self._int[:digits] or '0'
1609 if changed == 1:
1610 coeff = str(int(coeff)+1)
1611 ans = _dec_from_triple(self._sign, coeff, exp_min)
1612
1613 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001614 context._raise_error(Inexact)
1615 if self_is_subnormal:
1616 context._raise_error(Underflow)
1617 if not ans:
1618 # raise Clamped on underflow to 0
1619 context._raise_error(Clamped)
1620 elif len(ans._int) == context.prec+1:
1621 # we get here only if rescaling rounds the
1622 # cofficient up to exactly 10**context.prec
1623 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001624 ans = _dec_from_triple(ans._sign,
1625 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001626 else:
1627 # Inexact and Rounded have already been raised
1628 ans = context._raise_error(Overflow, 'above Emax',
1629 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001630 return ans
1631
Facundo Batista353750c2007-09-13 18:13:15 +00001632 # fold down if _clamp == 1 and self has too few digits
1633 if context._clamp == 1 and self._exp > Etop:
1634 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001635 self_padded = self._int + '0'*(self._exp - Etop)
1636 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001637
Facundo Batista353750c2007-09-13 18:13:15 +00001638 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001639 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001640
1641 _pick_rounding_function = {}
1642
Facundo Batista353750c2007-09-13 18:13:15 +00001643 # for each of the rounding functions below:
1644 # self is a finite, nonzero Decimal
1645 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001646 #
1647 # each function returns either -1, 0, or 1, as follows:
1648 # 1 indicates that self should be rounded up (away from zero)
1649 # 0 indicates that self should be truncated, and that all the
1650 # digits to be truncated are zeros (so the value is unchanged)
1651 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001652
1653 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001654 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001655 if _all_zeros(self._int, prec):
1656 return 0
1657 else:
1658 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001661 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001662 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001663
Facundo Batista353750c2007-09-13 18:13:15 +00001664 def _round_half_up(self, prec):
1665 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001666 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001667 return 1
1668 elif _all_zeros(self._int, prec):
1669 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001670 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001671 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001672
1673 def _round_half_down(self, prec):
1674 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001675 if _exact_half(self._int, prec):
1676 return -1
1677 else:
1678 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001679
1680 def _round_half_even(self, prec):
1681 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001682 if _exact_half(self._int, prec) and \
1683 (prec == 0 or self._int[prec-1] in '02468'):
1684 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001685 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001686 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001687
1688 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001689 """Rounds up (not away from 0 if negative.)"""
1690 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001691 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001693 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001694
Facundo Batista353750c2007-09-13 18:13:15 +00001695 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001696 """Rounds down (not towards 0 if negative)"""
1697 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001698 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001699 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001700 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001701
Facundo Batista353750c2007-09-13 18:13:15 +00001702 def _round_05up(self, prec):
1703 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001704 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001705 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001706 else:
1707 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001708
Facundo Batista353750c2007-09-13 18:13:15 +00001709 def fma(self, other, third, context=None):
1710 """Fused multiply-add.
1711
1712 Returns self*other+third with no rounding of the intermediate
1713 product self*other.
1714
1715 self and other are multiplied together, with no rounding of
1716 the result. The third operand is then added to the result,
1717 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001718 """
Facundo Batista353750c2007-09-13 18:13:15 +00001719
1720 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001721
1722 # compute product; raise InvalidOperation if either operand is
1723 # a signaling NaN or if the product is zero times infinity.
1724 if self._is_special or other._is_special:
1725 if context is None:
1726 context = getcontext()
1727 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001728 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001729 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001730 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001731 if self._exp == 'n':
1732 product = self
1733 elif other._exp == 'n':
1734 product = other
1735 elif self._exp == 'F':
1736 if not other:
1737 return context._raise_error(InvalidOperation,
1738 'INF * 0 in fma')
1739 product = Infsign[self._sign ^ other._sign]
1740 elif other._exp == 'F':
1741 if not self:
1742 return context._raise_error(InvalidOperation,
1743 '0 * INF in fma')
1744 product = Infsign[self._sign ^ other._sign]
1745 else:
1746 product = _dec_from_triple(self._sign ^ other._sign,
1747 str(int(self._int) * int(other._int)),
1748 self._exp + other._exp)
1749
Facundo Batista353750c2007-09-13 18:13:15 +00001750 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001751 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001752
Facundo Batista353750c2007-09-13 18:13:15 +00001753 def _power_modulo(self, other, modulo, context=None):
1754 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001755
Facundo Batista353750c2007-09-13 18:13:15 +00001756 # if can't convert other and modulo to Decimal, raise
1757 # TypeError; there's no point returning NotImplemented (no
1758 # equivalent of __rpow__ for three argument pow)
1759 other = _convert_other(other, raiseit=True)
1760 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001761
Facundo Batista353750c2007-09-13 18:13:15 +00001762 if context is None:
1763 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001764
Facundo Batista353750c2007-09-13 18:13:15 +00001765 # deal with NaNs: if there are any sNaNs then first one wins,
1766 # (i.e. behaviour for NaNs is identical to that of fma)
1767 self_is_nan = self._isnan()
1768 other_is_nan = other._isnan()
1769 modulo_is_nan = modulo._isnan()
1770 if self_is_nan or other_is_nan or modulo_is_nan:
1771 if self_is_nan == 2:
1772 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001773 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001774 if other_is_nan == 2:
1775 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001776 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001777 if modulo_is_nan == 2:
1778 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001779 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001780 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001781 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001782 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001783 return other._fix_nan(context)
1784 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001785
Facundo Batista353750c2007-09-13 18:13:15 +00001786 # check inputs: we apply same restrictions as Python's pow()
1787 if not (self._isinteger() and
1788 other._isinteger() and
1789 modulo._isinteger()):
1790 return context._raise_error(InvalidOperation,
1791 'pow() 3rd argument not allowed '
1792 'unless all arguments are integers')
1793 if other < 0:
1794 return context._raise_error(InvalidOperation,
1795 'pow() 2nd argument cannot be '
1796 'negative when 3rd argument specified')
1797 if not modulo:
1798 return context._raise_error(InvalidOperation,
1799 'pow() 3rd argument cannot be 0')
1800
1801 # additional restriction for decimal: the modulus must be less
1802 # than 10**prec in absolute value
1803 if modulo.adjusted() >= context.prec:
1804 return context._raise_error(InvalidOperation,
1805 'insufficient precision: pow() 3rd '
1806 'argument must not have more than '
1807 'precision digits')
1808
1809 # define 0**0 == NaN, for consistency with two-argument pow
1810 # (even though it hurts!)
1811 if not other and not self:
1812 return context._raise_error(InvalidOperation,
1813 'at least one of pow() 1st argument '
1814 'and 2nd argument must be nonzero ;'
1815 '0**0 is not defined')
1816
1817 # compute sign of result
1818 if other._iseven():
1819 sign = 0
1820 else:
1821 sign = self._sign
1822
1823 # convert modulo to a Python integer, and self and other to
1824 # Decimal integers (i.e. force their exponents to be >= 0)
1825 modulo = abs(int(modulo))
1826 base = _WorkRep(self.to_integral_value())
1827 exponent = _WorkRep(other.to_integral_value())
1828
1829 # compute result using integer pow()
1830 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1831 for i in xrange(exponent.exp):
1832 base = pow(base, 10, modulo)
1833 base = pow(base, exponent.int, modulo)
1834
Facundo Batista72bc54f2007-11-23 17:59:00 +00001835 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001836
1837 def _power_exact(self, other, p):
1838 """Attempt to compute self**other exactly.
1839
1840 Given Decimals self and other and an integer p, attempt to
1841 compute an exact result for the power self**other, with p
1842 digits of precision. Return None if self**other is not
1843 exactly representable in p digits.
1844
1845 Assumes that elimination of special cases has already been
1846 performed: self and other must both be nonspecial; self must
1847 be positive and not numerically equal to 1; other must be
1848 nonzero. For efficiency, other._exp should not be too large,
1849 so that 10**abs(other._exp) is a feasible calculation."""
1850
1851 # In the comments below, we write x for the value of self and
1852 # y for the value of other. Write x = xc*10**xe and y =
1853 # yc*10**ye.
1854
1855 # The main purpose of this method is to identify the *failure*
1856 # of x**y to be exactly representable with as little effort as
1857 # possible. So we look for cheap and easy tests that
1858 # eliminate the possibility of x**y being exact. Only if all
1859 # these tests are passed do we go on to actually compute x**y.
1860
1861 # Here's the main idea. First normalize both x and y. We
1862 # express y as a rational m/n, with m and n relatively prime
1863 # and n>0. Then for x**y to be exactly representable (at
1864 # *any* precision), xc must be the nth power of a positive
1865 # integer and xe must be divisible by n. If m is negative
1866 # then additionally xc must be a power of either 2 or 5, hence
1867 # a power of 2**n or 5**n.
1868 #
1869 # There's a limit to how small |y| can be: if y=m/n as above
1870 # then:
1871 #
1872 # (1) if xc != 1 then for the result to be representable we
1873 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1874 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1875 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1876 # representable.
1877 #
1878 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1879 # |y| < 1/|xe| then the result is not representable.
1880 #
1881 # Note that since x is not equal to 1, at least one of (1) and
1882 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1883 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1884 #
1885 # There's also a limit to how large y can be, at least if it's
1886 # positive: the normalized result will have coefficient xc**y,
1887 # so if it's representable then xc**y < 10**p, and y <
1888 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1889 # not exactly representable.
1890
1891 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1892 # so |y| < 1/xe and the result is not representable.
1893 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1894 # < 1/nbits(xc).
1895
1896 x = _WorkRep(self)
1897 xc, xe = x.int, x.exp
1898 while xc % 10 == 0:
1899 xc //= 10
1900 xe += 1
1901
1902 y = _WorkRep(other)
1903 yc, ye = y.int, y.exp
1904 while yc % 10 == 0:
1905 yc //= 10
1906 ye += 1
1907
1908 # case where xc == 1: result is 10**(xe*y), with xe*y
1909 # required to be an integer
1910 if xc == 1:
1911 if ye >= 0:
1912 exponent = xe*yc*10**ye
1913 else:
1914 exponent, remainder = divmod(xe*yc, 10**-ye)
1915 if remainder:
1916 return None
1917 if y.sign == 1:
1918 exponent = -exponent
1919 # if other is a nonnegative integer, use ideal exponent
1920 if other._isinteger() and other._sign == 0:
1921 ideal_exponent = self._exp*int(other)
1922 zeros = min(exponent-ideal_exponent, p-1)
1923 else:
1924 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001925 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001926
1927 # case where y is negative: xc must be either a power
1928 # of 2 or a power of 5.
1929 if y.sign == 1:
1930 last_digit = xc % 10
1931 if last_digit in (2,4,6,8):
1932 # quick test for power of 2
1933 if xc & -xc != xc:
1934 return None
1935 # now xc is a power of 2; e is its exponent
1936 e = _nbits(xc)-1
1937 # find e*y and xe*y; both must be integers
1938 if ye >= 0:
1939 y_as_int = yc*10**ye
1940 e = e*y_as_int
1941 xe = xe*y_as_int
1942 else:
1943 ten_pow = 10**-ye
1944 e, remainder = divmod(e*yc, ten_pow)
1945 if remainder:
1946 return None
1947 xe, remainder = divmod(xe*yc, ten_pow)
1948 if remainder:
1949 return None
1950
1951 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1952 return None
1953 xc = 5**e
1954
1955 elif last_digit == 5:
1956 # e >= log_5(xc) if xc is a power of 5; we have
1957 # equality all the way up to xc=5**2658
1958 e = _nbits(xc)*28//65
1959 xc, remainder = divmod(5**e, xc)
1960 if remainder:
1961 return None
1962 while xc % 5 == 0:
1963 xc //= 5
1964 e -= 1
1965 if ye >= 0:
1966 y_as_integer = yc*10**ye
1967 e = e*y_as_integer
1968 xe = xe*y_as_integer
1969 else:
1970 ten_pow = 10**-ye
1971 e, remainder = divmod(e*yc, ten_pow)
1972 if remainder:
1973 return None
1974 xe, remainder = divmod(xe*yc, ten_pow)
1975 if remainder:
1976 return None
1977 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1978 return None
1979 xc = 2**e
1980 else:
1981 return None
1982
1983 if xc >= 10**p:
1984 return None
1985 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001986 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001987
1988 # now y is positive; find m and n such that y = m/n
1989 if ye >= 0:
1990 m, n = yc*10**ye, 1
1991 else:
1992 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1993 return None
1994 xc_bits = _nbits(xc)
1995 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1996 return None
1997 m, n = yc, 10**(-ye)
1998 while m % 2 == n % 2 == 0:
1999 m //= 2
2000 n //= 2
2001 while m % 5 == n % 5 == 0:
2002 m //= 5
2003 n //= 5
2004
2005 # compute nth root of xc*10**xe
2006 if n > 1:
2007 # if 1 < xc < 2**n then xc isn't an nth power
2008 if xc != 1 and xc_bits <= n:
2009 return None
2010
2011 xe, rem = divmod(xe, n)
2012 if rem != 0:
2013 return None
2014
2015 # compute nth root of xc using Newton's method
2016 a = 1L << -(-_nbits(xc)//n) # initial estimate
2017 while True:
2018 q, r = divmod(xc, a**(n-1))
2019 if a <= q:
2020 break
2021 else:
2022 a = (a*(n-1) + q)//n
2023 if not (a == q and r == 0):
2024 return None
2025 xc = a
2026
2027 # now xc*10**xe is the nth root of the original xc*10**xe
2028 # compute mth power of xc*10**xe
2029
2030 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2031 # 10**p and the result is not representable.
2032 if xc > 1 and m > p*100//_log10_lb(xc):
2033 return None
2034 xc = xc**m
2035 xe *= m
2036 if xc > 10**p:
2037 return None
2038
2039 # by this point the result *is* exactly representable
2040 # adjust the exponent to get as close as possible to the ideal
2041 # exponent, if necessary
2042 str_xc = str(xc)
2043 if other._isinteger() and other._sign == 0:
2044 ideal_exponent = self._exp*int(other)
2045 zeros = min(xe-ideal_exponent, p-len(str_xc))
2046 else:
2047 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002048 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002049
2050 def __pow__(self, other, modulo=None, context=None):
2051 """Return self ** other [ % modulo].
2052
2053 With two arguments, compute self**other.
2054
2055 With three arguments, compute (self**other) % modulo. For the
2056 three argument form, the following restrictions on the
2057 arguments hold:
2058
2059 - all three arguments must be integral
2060 - other must be nonnegative
2061 - either self or other (or both) must be nonzero
2062 - modulo must be nonzero and must have at most p digits,
2063 where p is the context precision.
2064
2065 If any of these restrictions is violated the InvalidOperation
2066 flag is raised.
2067
2068 The result of pow(self, other, modulo) is identical to the
2069 result that would be obtained by computing (self**other) %
2070 modulo with unbounded precision, but is computed more
2071 efficiently. It is always exact.
2072 """
2073
2074 if modulo is not None:
2075 return self._power_modulo(other, modulo, context)
2076
2077 other = _convert_other(other)
2078 if other is NotImplemented:
2079 return other
2080
2081 if context is None:
2082 context = getcontext()
2083
2084 # either argument is a NaN => result is NaN
2085 ans = self._check_nans(other, context)
2086 if ans:
2087 return ans
2088
2089 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2090 if not other:
2091 if not self:
2092 return context._raise_error(InvalidOperation, '0 ** 0')
2093 else:
2094 return Dec_p1
2095
2096 # result has sign 1 iff self._sign is 1 and other is an odd integer
2097 result_sign = 0
2098 if self._sign == 1:
2099 if other._isinteger():
2100 if not other._iseven():
2101 result_sign = 1
2102 else:
2103 # -ve**noninteger = NaN
2104 # (-0)**noninteger = 0**noninteger
2105 if self:
2106 return context._raise_error(InvalidOperation,
2107 'x ** y with x negative and y not an integer')
2108 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002109 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002110
2111 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2112 if not self:
2113 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002114 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002115 else:
2116 return Infsign[result_sign]
2117
2118 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002119 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002120 if other._sign == 0:
2121 return Infsign[result_sign]
2122 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002123 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002124
Facundo Batista353750c2007-09-13 18:13:15 +00002125 # 1**other = 1, but the choice of exponent and the flags
2126 # depend on the exponent of self, and on whether other is a
2127 # positive integer, a negative integer, or neither
2128 if self == Dec_p1:
2129 if other._isinteger():
2130 # exp = max(self._exp*max(int(other), 0),
2131 # 1-context.prec) but evaluating int(other) directly
2132 # is dangerous until we know other is small (other
2133 # could be 1e999999999)
2134 if other._sign == 1:
2135 multiplier = 0
2136 elif other > context.prec:
2137 multiplier = context.prec
2138 else:
2139 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002140
Facundo Batista353750c2007-09-13 18:13:15 +00002141 exp = self._exp * multiplier
2142 if exp < 1-context.prec:
2143 exp = 1-context.prec
2144 context._raise_error(Rounded)
2145 else:
2146 context._raise_error(Inexact)
2147 context._raise_error(Rounded)
2148 exp = 1-context.prec
2149
Facundo Batista72bc54f2007-11-23 17:59:00 +00002150 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002151
2152 # compute adjusted exponent of self
2153 self_adj = self.adjusted()
2154
2155 # self ** infinity is infinity if self > 1, 0 if self < 1
2156 # self ** -infinity is infinity if self < 1, 0 if self > 1
2157 if other._isinfinity():
2158 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002159 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002160 else:
2161 return Infsign[result_sign]
2162
2163 # from here on, the result always goes through the call
2164 # to _fix at the end of this function.
2165 ans = None
2166
2167 # crude test to catch cases of extreme overflow/underflow. If
2168 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2169 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2170 # self**other >= 10**(Emax+1), so overflow occurs. The test
2171 # for underflow is similar.
2172 bound = self._log10_exp_bound() + other.adjusted()
2173 if (self_adj >= 0) == (other._sign == 0):
2174 # self > 1 and other +ve, or self < 1 and other -ve
2175 # possibility of overflow
2176 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002177 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002178 else:
2179 # self > 1 and other -ve, or self < 1 and other +ve
2180 # possibility of underflow to 0
2181 Etiny = context.Etiny()
2182 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002183 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002184
2185 # try for an exact result with precision +1
2186 if ans is None:
2187 ans = self._power_exact(other, context.prec + 1)
2188 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002189 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002190
2191 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2192 if ans is None:
2193 p = context.prec
2194 x = _WorkRep(self)
2195 xc, xe = x.int, x.exp
2196 y = _WorkRep(other)
2197 yc, ye = y.int, y.exp
2198 if y.sign == 1:
2199 yc = -yc
2200
2201 # compute correctly rounded result: start with precision +3,
2202 # then increase precision until result is unambiguously roundable
2203 extra = 3
2204 while True:
2205 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2206 if coeff % (5*10**(len(str(coeff))-p-1)):
2207 break
2208 extra += 3
2209
Facundo Batista72bc54f2007-11-23 17:59:00 +00002210 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002211
2212 # the specification says that for non-integer other we need to
2213 # raise Inexact, even when the result is actually exact. In
2214 # the same way, we need to raise Underflow here if the result
2215 # is subnormal. (The call to _fix will take care of raising
2216 # Rounded and Subnormal, as usual.)
2217 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002218 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002219 # pad with zeros up to length context.prec+1 if necessary
2220 if len(ans._int) <= context.prec:
2221 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002222 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2223 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002224 if ans.adjusted() < context.Emin:
2225 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002226
Facundo Batista353750c2007-09-13 18:13:15 +00002227 # unlike exp, ln and log10, the power function respects the
2228 # rounding mode; no need to use ROUND_HALF_EVEN here
2229 ans = ans._fix(context)
2230 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002231
2232 def __rpow__(self, other, context=None):
2233 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002234 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002235 if other is NotImplemented:
2236 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237 return other.__pow__(self, context=context)
2238
2239 def normalize(self, context=None):
2240 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002241
Facundo Batista353750c2007-09-13 18:13:15 +00002242 if context is None:
2243 context = getcontext()
2244
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002245 if self._is_special:
2246 ans = self._check_nans(context=context)
2247 if ans:
2248 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002249
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002250 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002251 if dup._isinfinity():
2252 return dup
2253
2254 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002255 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002256 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002257 end = len(dup._int)
2258 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002259 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002260 exp += 1
2261 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002262 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002263
Facundo Batistabd2fe832007-09-13 18:42:09 +00002264 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002265 """Quantize self so its exponent is the same as that of exp.
2266
2267 Similar to self._rescale(exp._exp) but with error checking.
2268 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002269 exp = _convert_other(exp, raiseit=True)
2270
Facundo Batista353750c2007-09-13 18:13:15 +00002271 if context is None:
2272 context = getcontext()
2273 if rounding is None:
2274 rounding = context.rounding
2275
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002276 if self._is_special or exp._is_special:
2277 ans = self._check_nans(exp, context)
2278 if ans:
2279 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002280
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002281 if exp._isinfinity() or self._isinfinity():
2282 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002283 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002284 return context._raise_error(InvalidOperation,
2285 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002286
Facundo Batistabd2fe832007-09-13 18:42:09 +00002287 # if we're not watching exponents, do a simple rescale
2288 if not watchexp:
2289 ans = self._rescale(exp._exp, rounding)
2290 # raise Inexact and Rounded where appropriate
2291 if ans._exp > self._exp:
2292 context._raise_error(Rounded)
2293 if ans != self:
2294 context._raise_error(Inexact)
2295 return ans
2296
Facundo Batista353750c2007-09-13 18:13:15 +00002297 # exp._exp should be between Etiny and Emax
2298 if not (context.Etiny() <= exp._exp <= context.Emax):
2299 return context._raise_error(InvalidOperation,
2300 'target exponent out of bounds in quantize')
2301
2302 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002303 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002304 return ans._fix(context)
2305
2306 self_adjusted = self.adjusted()
2307 if self_adjusted > context.Emax:
2308 return context._raise_error(InvalidOperation,
2309 'exponent of quantize result too large for current context')
2310 if self_adjusted - exp._exp + 1 > context.prec:
2311 return context._raise_error(InvalidOperation,
2312 'quantize result has too many digits for current context')
2313
2314 ans = self._rescale(exp._exp, rounding)
2315 if ans.adjusted() > context.Emax:
2316 return context._raise_error(InvalidOperation,
2317 'exponent of quantize result too large for current context')
2318 if len(ans._int) > context.prec:
2319 return context._raise_error(InvalidOperation,
2320 'quantize result has too many digits for current context')
2321
2322 # raise appropriate flags
2323 if ans._exp > self._exp:
2324 context._raise_error(Rounded)
2325 if ans != self:
2326 context._raise_error(Inexact)
2327 if ans and ans.adjusted() < context.Emin:
2328 context._raise_error(Subnormal)
2329
2330 # call to fix takes care of any necessary folddown
2331 ans = ans._fix(context)
2332 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
2334 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002335 """Return True if self and other have the same exponent; otherwise
2336 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002337
Facundo Batista1a191df2007-10-02 17:01:24 +00002338 If either operand is a special value, the following rules are used:
2339 * return True if both operands are infinities
2340 * return True if both operands are NaNs
2341 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002342 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002343 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002344 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002345 return (self.is_nan() and other.is_nan() or
2346 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002347 return self._exp == other._exp
2348
Facundo Batista353750c2007-09-13 18:13:15 +00002349 def _rescale(self, exp, rounding):
2350 """Rescale self so that the exponent is exp, either by padding with zeros
2351 or by truncating digits, using the given rounding mode.
2352
2353 Specials are returned without change. This operation is
2354 quiet: it raises no flags, and uses no information from the
2355 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002356
2357 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002358 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002359 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002360 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002361 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002362 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002363 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002364
Facundo Batista353750c2007-09-13 18:13:15 +00002365 if self._exp >= exp:
2366 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002367 return _dec_from_triple(self._sign,
2368 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369
Facundo Batista353750c2007-09-13 18:13:15 +00002370 # too many digits; round and lose data. If self.adjusted() <
2371 # exp-1, replace self by 10**(exp-1) before rounding
2372 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002373 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002374 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002375 digits = 0
2376 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002377 changed = this_function(digits)
2378 coeff = self._int[:digits] or '0'
2379 if changed == 1:
2380 coeff = str(int(coeff)+1)
2381 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002382
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002383 def _round(self, places, rounding):
2384 """Round a nonzero, nonspecial Decimal to a fixed number of
2385 significant figures, using the given rounding mode.
2386
2387 Infinities, NaNs and zeros are returned unaltered.
2388
2389 This operation is quiet: it raises no flags, and uses no
2390 information from the context.
2391
2392 """
2393 if places <= 0:
2394 raise ValueError("argument should be at least 1 in _round")
2395 if self._is_special or not self:
2396 return Decimal(self)
2397 ans = self._rescale(self.adjusted()+1-places, rounding)
2398 # it can happen that the rescale alters the adjusted exponent;
2399 # for example when rounding 99.97 to 3 significant figures.
2400 # When this happens we end up with an extra 0 at the end of
2401 # the number; a second rescale fixes this.
2402 if ans.adjusted() != self.adjusted():
2403 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2404 return ans
2405
Facundo Batista353750c2007-09-13 18:13:15 +00002406 def to_integral_exact(self, rounding=None, context=None):
2407 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Facundo Batista353750c2007-09-13 18:13:15 +00002409 If no rounding mode is specified, take the rounding mode from
2410 the context. This method raises the Rounded and Inexact flags
2411 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002412
Facundo Batista353750c2007-09-13 18:13:15 +00002413 See also: to_integral_value, which does exactly the same as
2414 this method except that it doesn't raise Inexact or Rounded.
2415 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002416 if self._is_special:
2417 ans = self._check_nans(context=context)
2418 if ans:
2419 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002420 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002421 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002422 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002423 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002424 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002425 if context is None:
2426 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002427 if rounding is None:
2428 rounding = context.rounding
2429 context._raise_error(Rounded)
2430 ans = self._rescale(0, rounding)
2431 if ans != self:
2432 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002433 return ans
2434
Facundo Batista353750c2007-09-13 18:13:15 +00002435 def to_integral_value(self, rounding=None, context=None):
2436 """Rounds to the nearest integer, without raising inexact, rounded."""
2437 if context is None:
2438 context = getcontext()
2439 if rounding is None:
2440 rounding = context.rounding
2441 if self._is_special:
2442 ans = self._check_nans(context=context)
2443 if ans:
2444 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002445 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002446 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002447 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002448 else:
2449 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002450
Facundo Batista353750c2007-09-13 18:13:15 +00002451 # the method name changed, but we provide also the old one, for compatibility
2452 to_integral = to_integral_value
2453
2454 def sqrt(self, context=None):
2455 """Return the square root of self."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002456 if self._is_special:
2457 ans = self._check_nans(context=context)
2458 if ans:
2459 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002460
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002461 if self._isinfinity() and self._sign == 0:
2462 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002463
2464 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002465 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002466 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002467 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002468
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002469 if context is None:
2470 context = getcontext()
2471
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002472 if self._sign == 1:
2473 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2474
Facundo Batista353750c2007-09-13 18:13:15 +00002475 # At this point self represents a positive number. Let p be
2476 # the desired precision and express self in the form c*100**e
2477 # with c a positive real number and e an integer, c and e
2478 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2479 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2480 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2481 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2482 # the closest integer to sqrt(c) with the even integer chosen
2483 # in the case of a tie.
2484 #
2485 # To ensure correct rounding in all cases, we use the
2486 # following trick: we compute the square root to an extra
2487 # place (precision p+1 instead of precision p), rounding down.
2488 # Then, if the result is inexact and its last digit is 0 or 5,
2489 # we increase the last digit to 1 or 6 respectively; if it's
2490 # exact we leave the last digit alone. Now the final round to
2491 # p places (or fewer in the case of underflow) will round
2492 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002493
Facundo Batista353750c2007-09-13 18:13:15 +00002494 # use an extra digit of precision
2495 prec = context.prec+1
2496
2497 # write argument in the form c*100**e where e = self._exp//2
2498 # is the 'ideal' exponent, to be used if the square root is
2499 # exactly representable. l is the number of 'digits' of c in
2500 # base 100, so that 100**(l-1) <= c < 100**l.
2501 op = _WorkRep(self)
2502 e = op.exp >> 1
2503 if op.exp & 1:
2504 c = op.int * 10
2505 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002506 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002507 c = op.int
2508 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002509
Facundo Batista353750c2007-09-13 18:13:15 +00002510 # rescale so that c has exactly prec base 100 'digits'
2511 shift = prec-l
2512 if shift >= 0:
2513 c *= 100**shift
2514 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002515 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002516 c, remainder = divmod(c, 100**-shift)
2517 exact = not remainder
2518 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002519
Facundo Batista353750c2007-09-13 18:13:15 +00002520 # find n = floor(sqrt(c)) using Newton's method
2521 n = 10**prec
2522 while True:
2523 q = c//n
2524 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525 break
Facundo Batista353750c2007-09-13 18:13:15 +00002526 else:
2527 n = n + q >> 1
2528 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002529
Facundo Batista353750c2007-09-13 18:13:15 +00002530 if exact:
2531 # result is exact; rescale to use ideal exponent e
2532 if shift >= 0:
2533 # assert n % 10**shift == 0
2534 n //= 10**shift
2535 else:
2536 n *= 10**-shift
2537 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002539 # result is not exact; fix last digit as described above
2540 if n % 5 == 0:
2541 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002542
Facundo Batista72bc54f2007-11-23 17:59:00 +00002543 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002544
Facundo Batista353750c2007-09-13 18:13:15 +00002545 # round, and fit to current context
2546 context = context._shallow_copy()
2547 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002548 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002549 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002550
Facundo Batista353750c2007-09-13 18:13:15 +00002551 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002552
2553 def max(self, other, context=None):
2554 """Returns the larger value.
2555
Facundo Batista353750c2007-09-13 18:13:15 +00002556 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002557 NaN (and signals if one is sNaN). Also rounds.
2558 """
Facundo Batista353750c2007-09-13 18:13:15 +00002559 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002560
Facundo Batista6c398da2007-09-17 17:30:13 +00002561 if context is None:
2562 context = getcontext()
2563
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002564 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002565 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002566 # number is always returned
2567 sn = self._isnan()
2568 on = other._isnan()
2569 if sn or on:
2570 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002571 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002572 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002573 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002574 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002575
Mark Dickinson2fc92632008-02-06 22:10:50 +00002576 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002577 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002578 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002579 # then an ordering is applied:
2580 #
Facundo Batista59c58842007-04-10 12:58:45 +00002581 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002582 # positive sign and min returns the operand with the negative sign
2583 #
Facundo Batista59c58842007-04-10 12:58:45 +00002584 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002585 # the result. This is exactly the ordering used in compare_total.
2586 c = self.compare_total(other)
2587
2588 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002589 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002590 else:
2591 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002592
Facundo Batistae64acfa2007-12-17 14:18:42 +00002593 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002594
2595 def min(self, other, context=None):
2596 """Returns the smaller value.
2597
Facundo Batista59c58842007-04-10 12:58:45 +00002598 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002599 NaN (and signals if one is sNaN). Also rounds.
2600 """
Facundo Batista353750c2007-09-13 18:13:15 +00002601 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002602
Facundo Batista6c398da2007-09-17 17:30:13 +00002603 if context is None:
2604 context = getcontext()
2605
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002606 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002607 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002608 # number is always returned
2609 sn = self._isnan()
2610 on = other._isnan()
2611 if sn or on:
2612 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002613 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002614 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002615 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002616 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002617
Mark Dickinson2fc92632008-02-06 22:10:50 +00002618 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002619 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002620 c = self.compare_total(other)
2621
2622 if c == -1:
2623 ans = self
2624 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002625 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002626
Facundo Batistae64acfa2007-12-17 14:18:42 +00002627 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002628
2629 def _isinteger(self):
2630 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002631 if self._is_special:
2632 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633 if self._exp >= 0:
2634 return True
2635 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002636 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002637
2638 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002639 """Returns True if self is even. Assumes self is an integer."""
2640 if not self or self._exp > 0:
2641 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002642 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002643
2644 def adjusted(self):
2645 """Return the adjusted exponent of self"""
2646 try:
2647 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002648 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002649 except TypeError:
2650 return 0
2651
Facundo Batista353750c2007-09-13 18:13:15 +00002652 def canonical(self, context=None):
2653 """Returns the same Decimal object.
2654
2655 As we do not have different encodings for the same number, the
2656 received object already is in its canonical form.
2657 """
2658 return self
2659
2660 def compare_signal(self, other, context=None):
2661 """Compares self to the other operand numerically.
2662
2663 It's pretty much like compare(), but all NaNs signal, with signaling
2664 NaNs taking precedence over quiet NaNs.
2665 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002666 other = _convert_other(other, raiseit = True)
2667 ans = self._compare_check_nans(other, context)
2668 if ans:
2669 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002670 return self.compare(other, context=context)
2671
2672 def compare_total(self, other):
2673 """Compares self to other using the abstract representations.
2674
2675 This is not like the standard compare, which use their numerical
2676 value. Note that a total ordering is defined for all possible abstract
2677 representations.
2678 """
2679 # if one is negative and the other is positive, it's easy
2680 if self._sign and not other._sign:
2681 return Dec_n1
2682 if not self._sign and other._sign:
2683 return Dec_p1
2684 sign = self._sign
2685
2686 # let's handle both NaN types
2687 self_nan = self._isnan()
2688 other_nan = other._isnan()
2689 if self_nan or other_nan:
2690 if self_nan == other_nan:
2691 if self._int < other._int:
2692 if sign:
2693 return Dec_p1
2694 else:
2695 return Dec_n1
2696 if self._int > other._int:
2697 if sign:
2698 return Dec_n1
2699 else:
2700 return Dec_p1
2701 return Dec_0
2702
2703 if sign:
2704 if self_nan == 1:
2705 return Dec_n1
2706 if other_nan == 1:
2707 return Dec_p1
2708 if self_nan == 2:
2709 return Dec_n1
2710 if other_nan == 2:
2711 return Dec_p1
2712 else:
2713 if self_nan == 1:
2714 return Dec_p1
2715 if other_nan == 1:
2716 return Dec_n1
2717 if self_nan == 2:
2718 return Dec_p1
2719 if other_nan == 2:
2720 return Dec_n1
2721
2722 if self < other:
2723 return Dec_n1
2724 if self > other:
2725 return Dec_p1
2726
2727 if self._exp < other._exp:
2728 if sign:
2729 return Dec_p1
2730 else:
2731 return Dec_n1
2732 if self._exp > other._exp:
2733 if sign:
2734 return Dec_n1
2735 else:
2736 return Dec_p1
2737 return Dec_0
2738
2739
2740 def compare_total_mag(self, other):
2741 """Compares self to other using abstract repr., ignoring sign.
2742
2743 Like compare_total, but with operand's sign ignored and assumed to be 0.
2744 """
2745 s = self.copy_abs()
2746 o = other.copy_abs()
2747 return s.compare_total(o)
2748
2749 def copy_abs(self):
2750 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002751 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002752
2753 def copy_negate(self):
2754 """Returns a copy with the sign inverted."""
2755 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002756 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002757 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002758 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002759
2760 def copy_sign(self, other):
2761 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002762 return _dec_from_triple(other._sign, self._int,
2763 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002764
2765 def exp(self, context=None):
2766 """Returns e ** self."""
2767
2768 if context is None:
2769 context = getcontext()
2770
2771 # exp(NaN) = NaN
2772 ans = self._check_nans(context=context)
2773 if ans:
2774 return ans
2775
2776 # exp(-Infinity) = 0
2777 if self._isinfinity() == -1:
2778 return Dec_0
2779
2780 # exp(0) = 1
2781 if not self:
2782 return Dec_p1
2783
2784 # exp(Infinity) = Infinity
2785 if self._isinfinity() == 1:
2786 return Decimal(self)
2787
2788 # the result is now guaranteed to be inexact (the true
2789 # mathematical result is transcendental). There's no need to
2790 # raise Rounded and Inexact here---they'll always be raised as
2791 # a result of the call to _fix.
2792 p = context.prec
2793 adj = self.adjusted()
2794
2795 # we only need to do any computation for quite a small range
2796 # of adjusted exponents---for example, -29 <= adj <= 10 for
2797 # the default context. For smaller exponent the result is
2798 # indistinguishable from 1 at the given precision, while for
2799 # larger exponent the result either overflows or underflows.
2800 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2801 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002802 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002803 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2804 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002805 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002806 elif self._sign == 0 and adj < -p:
2807 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002808 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002809 elif self._sign == 1 and adj < -p-1:
2810 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002811 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002812 # general case
2813 else:
2814 op = _WorkRep(self)
2815 c, e = op.int, op.exp
2816 if op.sign == 1:
2817 c = -c
2818
2819 # compute correctly rounded result: increase precision by
2820 # 3 digits at a time until we get an unambiguously
2821 # roundable result
2822 extra = 3
2823 while True:
2824 coeff, exp = _dexp(c, e, p+extra)
2825 if coeff % (5*10**(len(str(coeff))-p-1)):
2826 break
2827 extra += 3
2828
Facundo Batista72bc54f2007-11-23 17:59:00 +00002829 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002830
2831 # at this stage, ans should round correctly with *any*
2832 # rounding mode, not just with ROUND_HALF_EVEN
2833 context = context._shallow_copy()
2834 rounding = context._set_rounding(ROUND_HALF_EVEN)
2835 ans = ans._fix(context)
2836 context.rounding = rounding
2837
2838 return ans
2839
2840 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002841 """Return True if self is canonical; otherwise return False.
2842
2843 Currently, the encoding of a Decimal instance is always
2844 canonical, so this method returns True for any Decimal.
2845 """
2846 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002847
2848 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002849 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002850
Facundo Batista1a191df2007-10-02 17:01:24 +00002851 A Decimal instance is considered finite if it is neither
2852 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002853 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002854 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002855
2856 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002857 """Return True if self is infinite; otherwise return False."""
2858 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002859
2860 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002861 """Return True if self is a qNaN or sNaN; otherwise return False."""
2862 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002863
2864 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002865 """Return True if self is a normal number; otherwise return False."""
2866 if self._is_special or not self:
2867 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002868 if context is None:
2869 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002870 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002871
2872 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002873 """Return True if self is a quiet NaN; otherwise return False."""
2874 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002875
2876 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002877 """Return True if self is negative; otherwise return False."""
2878 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002879
2880 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002881 """Return True if self is a signaling NaN; otherwise return False."""
2882 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002883
2884 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002885 """Return True if self is subnormal; otherwise return False."""
2886 if self._is_special or not self:
2887 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002888 if context is None:
2889 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002890 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002891
2892 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002893 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002894 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002895
2896 def _ln_exp_bound(self):
2897 """Compute a lower bound for the adjusted exponent of self.ln().
2898 In other words, compute r such that self.ln() >= 10**r. Assumes
2899 that self is finite and positive and that self != 1.
2900 """
2901
2902 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2903 adj = self._exp + len(self._int) - 1
2904 if adj >= 1:
2905 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2906 return len(str(adj*23//10)) - 1
2907 if adj <= -2:
2908 # argument <= 0.1
2909 return len(str((-1-adj)*23//10)) - 1
2910 op = _WorkRep(self)
2911 c, e = op.int, op.exp
2912 if adj == 0:
2913 # 1 < self < 10
2914 num = str(c-10**-e)
2915 den = str(c)
2916 return len(num) - len(den) - (num < den)
2917 # adj == -1, 0.1 <= self < 1
2918 return e + len(str(10**-e - c)) - 1
2919
2920
2921 def ln(self, context=None):
2922 """Returns the natural (base e) logarithm of self."""
2923
2924 if context is None:
2925 context = getcontext()
2926
2927 # ln(NaN) = NaN
2928 ans = self._check_nans(context=context)
2929 if ans:
2930 return ans
2931
2932 # ln(0.0) == -Infinity
2933 if not self:
2934 return negInf
2935
2936 # ln(Infinity) = Infinity
2937 if self._isinfinity() == 1:
2938 return Inf
2939
2940 # ln(1.0) == 0.0
2941 if self == Dec_p1:
2942 return Dec_0
2943
2944 # ln(negative) raises InvalidOperation
2945 if self._sign == 1:
2946 return context._raise_error(InvalidOperation,
2947 'ln of a negative value')
2948
2949 # result is irrational, so necessarily inexact
2950 op = _WorkRep(self)
2951 c, e = op.int, op.exp
2952 p = context.prec
2953
2954 # correctly rounded result: repeatedly increase precision by 3
2955 # until we get an unambiguously roundable result
2956 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2957 while True:
2958 coeff = _dlog(c, e, places)
2959 # assert len(str(abs(coeff)))-p >= 1
2960 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2961 break
2962 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002963 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002964
2965 context = context._shallow_copy()
2966 rounding = context._set_rounding(ROUND_HALF_EVEN)
2967 ans = ans._fix(context)
2968 context.rounding = rounding
2969 return ans
2970
2971 def _log10_exp_bound(self):
2972 """Compute a lower bound for the adjusted exponent of self.log10().
2973 In other words, find r such that self.log10() >= 10**r.
2974 Assumes that self is finite and positive and that self != 1.
2975 """
2976
2977 # For x >= 10 or x < 0.1 we only need a bound on the integer
2978 # part of log10(self), and this comes directly from the
2979 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2980 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2981 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2982
2983 adj = self._exp + len(self._int) - 1
2984 if adj >= 1:
2985 # self >= 10
2986 return len(str(adj))-1
2987 if adj <= -2:
2988 # self < 0.1
2989 return len(str(-1-adj))-1
2990 op = _WorkRep(self)
2991 c, e = op.int, op.exp
2992 if adj == 0:
2993 # 1 < self < 10
2994 num = str(c-10**-e)
2995 den = str(231*c)
2996 return len(num) - len(den) - (num < den) + 2
2997 # adj == -1, 0.1 <= self < 1
2998 num = str(10**-e-c)
2999 return len(num) + e - (num < "231") - 1
3000
3001 def log10(self, context=None):
3002 """Returns the base 10 logarithm of self."""
3003
3004 if context is None:
3005 context = getcontext()
3006
3007 # log10(NaN) = NaN
3008 ans = self._check_nans(context=context)
3009 if ans:
3010 return ans
3011
3012 # log10(0.0) == -Infinity
3013 if not self:
3014 return negInf
3015
3016 # log10(Infinity) = Infinity
3017 if self._isinfinity() == 1:
3018 return Inf
3019
3020 # log10(negative or -Infinity) raises InvalidOperation
3021 if self._sign == 1:
3022 return context._raise_error(InvalidOperation,
3023 'log10 of a negative value')
3024
3025 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003026 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003027 # answer may need rounding
3028 ans = Decimal(self._exp + len(self._int) - 1)
3029 else:
3030 # result is irrational, so necessarily inexact
3031 op = _WorkRep(self)
3032 c, e = op.int, op.exp
3033 p = context.prec
3034
3035 # correctly rounded result: repeatedly increase precision
3036 # until result is unambiguously roundable
3037 places = p-self._log10_exp_bound()+2
3038 while True:
3039 coeff = _dlog10(c, e, places)
3040 # assert len(str(abs(coeff)))-p >= 1
3041 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3042 break
3043 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003044 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003045
3046 context = context._shallow_copy()
3047 rounding = context._set_rounding(ROUND_HALF_EVEN)
3048 ans = ans._fix(context)
3049 context.rounding = rounding
3050 return ans
3051
3052 def logb(self, context=None):
3053 """ Returns the exponent of the magnitude of self's MSD.
3054
3055 The result is the integer which is the exponent of the magnitude
3056 of the most significant digit of self (as though it were truncated
3057 to a single digit while maintaining the value of that digit and
3058 without limiting the resulting exponent).
3059 """
3060 # logb(NaN) = NaN
3061 ans = self._check_nans(context=context)
3062 if ans:
3063 return ans
3064
3065 if context is None:
3066 context = getcontext()
3067
3068 # logb(+/-Inf) = +Inf
3069 if self._isinfinity():
3070 return Inf
3071
3072 # logb(0) = -Inf, DivisionByZero
3073 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003074 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003075
3076 # otherwise, simply return the adjusted exponent of self, as a
3077 # Decimal. Note that no attempt is made to fit the result
3078 # into the current context.
3079 return Decimal(self.adjusted())
3080
3081 def _islogical(self):
3082 """Return True if self is a logical operand.
3083
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003084 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003085 an exponent of 0, and a coefficient whose digits must all be
3086 either 0 or 1.
3087 """
3088 if self._sign != 0 or self._exp != 0:
3089 return False
3090 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003091 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003092 return False
3093 return True
3094
3095 def _fill_logical(self, context, opa, opb):
3096 dif = context.prec - len(opa)
3097 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003098 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003099 elif dif < 0:
3100 opa = opa[-context.prec:]
3101 dif = context.prec - len(opb)
3102 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003103 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003104 elif dif < 0:
3105 opb = opb[-context.prec:]
3106 return opa, opb
3107
3108 def logical_and(self, other, context=None):
3109 """Applies an 'and' operation between self and other's digits."""
3110 if context is None:
3111 context = getcontext()
3112 if not self._islogical() or not other._islogical():
3113 return context._raise_error(InvalidOperation)
3114
3115 # fill to context.prec
3116 (opa, opb) = self._fill_logical(context, self._int, other._int)
3117
3118 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003119 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3120 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003121
3122 def logical_invert(self, context=None):
3123 """Invert all its digits."""
3124 if context is None:
3125 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003126 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3127 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003128
3129 def logical_or(self, other, context=None):
3130 """Applies an 'or' operation between self and other's digits."""
3131 if context is None:
3132 context = getcontext()
3133 if not self._islogical() or not other._islogical():
3134 return context._raise_error(InvalidOperation)
3135
3136 # fill to context.prec
3137 (opa, opb) = self._fill_logical(context, self._int, other._int)
3138
3139 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003140 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3141 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003142
3143 def logical_xor(self, other, context=None):
3144 """Applies an 'xor' operation between self and other's digits."""
3145 if context is None:
3146 context = getcontext()
3147 if not self._islogical() or not other._islogical():
3148 return context._raise_error(InvalidOperation)
3149
3150 # fill to context.prec
3151 (opa, opb) = self._fill_logical(context, self._int, other._int)
3152
3153 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003154 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3155 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003156
3157 def max_mag(self, other, context=None):
3158 """Compares the values numerically with their sign ignored."""
3159 other = _convert_other(other, raiseit=True)
3160
Facundo Batista6c398da2007-09-17 17:30:13 +00003161 if context is None:
3162 context = getcontext()
3163
Facundo Batista353750c2007-09-13 18:13:15 +00003164 if self._is_special or other._is_special:
3165 # If one operand is a quiet NaN and the other is number, then the
3166 # number is always returned
3167 sn = self._isnan()
3168 on = other._isnan()
3169 if sn or on:
3170 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003171 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003172 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003173 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003174 return self._check_nans(other, context)
3175
Mark Dickinson2fc92632008-02-06 22:10:50 +00003176 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003177 if c == 0:
3178 c = self.compare_total(other)
3179
3180 if c == -1:
3181 ans = other
3182 else:
3183 ans = self
3184
Facundo Batistae64acfa2007-12-17 14:18:42 +00003185 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003186
3187 def min_mag(self, other, context=None):
3188 """Compares the values numerically with their sign ignored."""
3189 other = _convert_other(other, raiseit=True)
3190
Facundo Batista6c398da2007-09-17 17:30:13 +00003191 if context is None:
3192 context = getcontext()
3193
Facundo Batista353750c2007-09-13 18:13:15 +00003194 if self._is_special or other._is_special:
3195 # If one operand is a quiet NaN and the other is number, then the
3196 # number is always returned
3197 sn = self._isnan()
3198 on = other._isnan()
3199 if sn or on:
3200 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003201 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003202 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003203 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003204 return self._check_nans(other, context)
3205
Mark Dickinson2fc92632008-02-06 22:10:50 +00003206 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003207 if c == 0:
3208 c = self.compare_total(other)
3209
3210 if c == -1:
3211 ans = self
3212 else:
3213 ans = other
3214
Facundo Batistae64acfa2007-12-17 14:18:42 +00003215 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003216
3217 def next_minus(self, context=None):
3218 """Returns the largest representable number smaller than itself."""
3219 if context is None:
3220 context = getcontext()
3221
3222 ans = self._check_nans(context=context)
3223 if ans:
3224 return ans
3225
3226 if self._isinfinity() == -1:
3227 return negInf
3228 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003229 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003230
3231 context = context.copy()
3232 context._set_rounding(ROUND_FLOOR)
3233 context._ignore_all_flags()
3234 new_self = self._fix(context)
3235 if new_self != self:
3236 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003237 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3238 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003239
3240 def next_plus(self, context=None):
3241 """Returns the smallest representable number larger than itself."""
3242 if context is None:
3243 context = getcontext()
3244
3245 ans = self._check_nans(context=context)
3246 if ans:
3247 return ans
3248
3249 if self._isinfinity() == 1:
3250 return Inf
3251 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003252 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003253
3254 context = context.copy()
3255 context._set_rounding(ROUND_CEILING)
3256 context._ignore_all_flags()
3257 new_self = self._fix(context)
3258 if new_self != self:
3259 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003260 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3261 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003262
3263 def next_toward(self, other, context=None):
3264 """Returns the number closest to self, in the direction towards other.
3265
3266 The result is the closest representable number to self
3267 (excluding self) that is in the direction towards other,
3268 unless both have the same value. If the two operands are
3269 numerically equal, then the result is a copy of self with the
3270 sign set to be the same as the sign of other.
3271 """
3272 other = _convert_other(other, raiseit=True)
3273
3274 if context is None:
3275 context = getcontext()
3276
3277 ans = self._check_nans(other, context)
3278 if ans:
3279 return ans
3280
Mark Dickinson2fc92632008-02-06 22:10:50 +00003281 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003282 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003283 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003284
3285 if comparison == -1:
3286 ans = self.next_plus(context)
3287 else: # comparison == 1
3288 ans = self.next_minus(context)
3289
3290 # decide which flags to raise using value of ans
3291 if ans._isinfinity():
3292 context._raise_error(Overflow,
3293 'Infinite result from next_toward',
3294 ans._sign)
3295 context._raise_error(Rounded)
3296 context._raise_error(Inexact)
3297 elif ans.adjusted() < context.Emin:
3298 context._raise_error(Underflow)
3299 context._raise_error(Subnormal)
3300 context._raise_error(Rounded)
3301 context._raise_error(Inexact)
3302 # if precision == 1 then we don't raise Clamped for a
3303 # result 0E-Etiny.
3304 if not ans:
3305 context._raise_error(Clamped)
3306
3307 return ans
3308
3309 def number_class(self, context=None):
3310 """Returns an indication of the class of self.
3311
3312 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003313 sNaN
3314 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003315 -Infinity
3316 -Normal
3317 -Subnormal
3318 -Zero
3319 +Zero
3320 +Subnormal
3321 +Normal
3322 +Infinity
3323 """
3324 if self.is_snan():
3325 return "sNaN"
3326 if self.is_qnan():
3327 return "NaN"
3328 inf = self._isinfinity()
3329 if inf == 1:
3330 return "+Infinity"
3331 if inf == -1:
3332 return "-Infinity"
3333 if self.is_zero():
3334 if self._sign:
3335 return "-Zero"
3336 else:
3337 return "+Zero"
3338 if context is None:
3339 context = getcontext()
3340 if self.is_subnormal(context=context):
3341 if self._sign:
3342 return "-Subnormal"
3343 else:
3344 return "+Subnormal"
3345 # just a normal, regular, boring number, :)
3346 if self._sign:
3347 return "-Normal"
3348 else:
3349 return "+Normal"
3350
3351 def radix(self):
3352 """Just returns 10, as this is Decimal, :)"""
3353 return Decimal(10)
3354
3355 def rotate(self, other, context=None):
3356 """Returns a rotated copy of self, value-of-other times."""
3357 if context is None:
3358 context = getcontext()
3359
3360 ans = self._check_nans(other, context)
3361 if ans:
3362 return ans
3363
3364 if other._exp != 0:
3365 return context._raise_error(InvalidOperation)
3366 if not (-context.prec <= int(other) <= context.prec):
3367 return context._raise_error(InvalidOperation)
3368
3369 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003370 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003371
3372 # get values, pad if necessary
3373 torot = int(other)
3374 rotdig = self._int
3375 topad = context.prec - len(rotdig)
3376 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003377 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003378
3379 # let's rotate!
3380 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003381 return _dec_from_triple(self._sign,
3382 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003383
3384 def scaleb (self, other, context=None):
3385 """Returns self operand after adding the second value to its exp."""
3386 if context is None:
3387 context = getcontext()
3388
3389 ans = self._check_nans(other, context)
3390 if ans:
3391 return ans
3392
3393 if other._exp != 0:
3394 return context._raise_error(InvalidOperation)
3395 liminf = -2 * (context.Emax + context.prec)
3396 limsup = 2 * (context.Emax + context.prec)
3397 if not (liminf <= int(other) <= limsup):
3398 return context._raise_error(InvalidOperation)
3399
3400 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003401 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003402
Facundo Batista72bc54f2007-11-23 17:59:00 +00003403 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003404 d = d._fix(context)
3405 return d
3406
3407 def shift(self, other, context=None):
3408 """Returns a shifted copy of self, value-of-other times."""
3409 if context is None:
3410 context = getcontext()
3411
3412 ans = self._check_nans(other, context)
3413 if ans:
3414 return ans
3415
3416 if other._exp != 0:
3417 return context._raise_error(InvalidOperation)
3418 if not (-context.prec <= int(other) <= context.prec):
3419 return context._raise_error(InvalidOperation)
3420
3421 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003422 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003423
3424 # get values, pad if necessary
3425 torot = int(other)
3426 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003427 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003428 rotdig = self._int
3429 topad = context.prec - len(rotdig)
3430 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003431 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003432
3433 # let's shift!
3434 if torot < 0:
3435 rotated = rotdig[:torot]
3436 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003437 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003438 rotated = rotated[-context.prec:]
3439
Facundo Batista72bc54f2007-11-23 17:59:00 +00003440 return _dec_from_triple(self._sign,
3441 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003442
Facundo Batista59c58842007-04-10 12:58:45 +00003443 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003444 def __reduce__(self):
3445 return (self.__class__, (str(self),))
3446
3447 def __copy__(self):
3448 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003449 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003450 return self.__class__(str(self))
3451
3452 def __deepcopy__(self, memo):
3453 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003454 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003455 return self.__class__(str(self))
3456
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003457 # PEP 3101 support. See also _parse_format_specifier and _format_align
3458 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003459 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003460
3461 The specifier should be a standard format specifier, with the
3462 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3463 'F', 'g', 'G', and '%' are supported. If the formatting type
3464 is omitted it defaults to 'g' or 'G', depending on the value
3465 of context.capitals.
3466
3467 At this time the 'n' format specifier type (which is supposed
3468 to use the current locale) is not supported.
3469 """
3470
3471 # Note: PEP 3101 says that if the type is not present then
3472 # there should be at least one digit after the decimal point.
3473 # We take the liberty of ignoring this requirement for
3474 # Decimal---it's presumably there to make sure that
3475 # format(float, '') behaves similarly to str(float).
3476 if context is None:
3477 context = getcontext()
3478
3479 spec = _parse_format_specifier(specifier)
3480
3481 # special values don't care about the type or precision...
3482 if self._is_special:
3483 return _format_align(str(self), spec)
3484
3485 # a type of None defaults to 'g' or 'G', depending on context
3486 # if type is '%', adjust exponent of self accordingly
3487 if spec['type'] is None:
3488 spec['type'] = ['g', 'G'][context.capitals]
3489 elif spec['type'] == '%':
3490 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3491
3492 # round if necessary, taking rounding mode from the context
3493 rounding = context.rounding
3494 precision = spec['precision']
3495 if precision is not None:
3496 if spec['type'] in 'eE':
3497 self = self._round(precision+1, rounding)
3498 elif spec['type'] in 'gG':
3499 if len(self._int) > precision:
3500 self = self._round(precision, rounding)
3501 elif spec['type'] in 'fF%':
3502 self = self._rescale(-precision, rounding)
3503 # special case: zeros with a positive exponent can't be
3504 # represented in fixed point; rescale them to 0e0.
3505 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3506 self = self._rescale(0, rounding)
3507
3508 # figure out placement of the decimal point
3509 leftdigits = self._exp + len(self._int)
3510 if spec['type'] in 'fF%':
3511 dotplace = leftdigits
3512 elif spec['type'] in 'eE':
3513 if not self and precision is not None:
3514 dotplace = 1 - precision
3515 else:
3516 dotplace = 1
3517 elif spec['type'] in 'gG':
3518 if self._exp <= 0 and leftdigits > -6:
3519 dotplace = leftdigits
3520 else:
3521 dotplace = 1
3522
3523 # figure out main part of numeric string...
3524 if dotplace <= 0:
3525 num = '0.' + '0'*(-dotplace) + self._int
3526 elif dotplace >= len(self._int):
3527 # make sure we're not padding a '0' with extra zeros on the right
3528 assert dotplace==len(self._int) or self._int != '0'
3529 num = self._int + '0'*(dotplace-len(self._int))
3530 else:
3531 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3532
3533 # ...then the trailing exponent, or trailing '%'
3534 if leftdigits != dotplace or spec['type'] in 'eE':
3535 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3536 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3537 elif spec['type'] == '%':
3538 num = num + '%'
3539
3540 # add sign
3541 if self._sign == 1:
3542 num = '-' + num
3543 return _format_align(num, spec)
3544
3545
Facundo Batista72bc54f2007-11-23 17:59:00 +00003546def _dec_from_triple(sign, coefficient, exponent, special=False):
3547 """Create a decimal instance directly, without any validation,
3548 normalization (e.g. removal of leading zeros) or argument
3549 conversion.
3550
3551 This function is for *internal use only*.
3552 """
3553
3554 self = object.__new__(Decimal)
3555 self._sign = sign
3556 self._int = coefficient
3557 self._exp = exponent
3558 self._is_special = special
3559
3560 return self
3561
Facundo Batista59c58842007-04-10 12:58:45 +00003562##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003563
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003564
3565# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003566rounding_functions = [name for name in Decimal.__dict__.keys()
3567 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003568for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003569 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003570 globalname = name[1:].upper()
3571 val = globals()[globalname]
3572 Decimal._pick_rounding_function[val] = name
3573
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003574del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003575
Nick Coghlanced12182006-09-02 03:54:17 +00003576class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003577 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003578
Nick Coghlanced12182006-09-02 03:54:17 +00003579 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003580 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003581 """
3582 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003583 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003584 def __enter__(self):
3585 self.saved_context = getcontext()
3586 setcontext(self.new_context)
3587 return self.new_context
3588 def __exit__(self, t, v, tb):
3589 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003590
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003591class Context(object):
3592 """Contains the context for a Decimal instance.
3593
3594 Contains:
3595 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003596 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003597 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003598 raised when it is caused. Otherwise, a value is
3599 substituted in.
3600 flags - When an exception is caused, flags[exception] is incremented.
3601 (Whether or not the trap_enabler is set)
3602 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003603 Emin - Minimum exponent
3604 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003605 capitals - If 1, 1*10^1 is printed as 1E+1.
3606 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003607 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003608 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003609
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003610 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003611 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003612 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003613 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003614 _ignored_flags=None):
3615 if flags is None:
3616 flags = []
3617 if _ignored_flags is None:
3618 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003619 if not isinstance(flags, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003620 flags = dict([(s,s in flags) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003621 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003622 if traps is not None and not isinstance(traps, dict):
Raymond Hettingerfed52962004-07-14 15:41:57 +00003623 traps = dict([(s,s in traps) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003624 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003625 for name, val in locals().items():
3626 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003627 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003628 else:
3629 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003630 del self.self
3631
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003632 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003633 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003634 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003635 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3636 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3637 % vars(self))
3638 names = [f.__name__ for f, v in self.flags.items() if v]
3639 s.append('flags=[' + ', '.join(names) + ']')
3640 names = [t.__name__ for t, v in self.traps.items() if v]
3641 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003642 return ', '.join(s) + ')'
3643
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003644 def clear_flags(self):
3645 """Reset all flags to zero"""
3646 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003647 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003648
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003649 def _shallow_copy(self):
3650 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003651 nc = Context(self.prec, self.rounding, self.traps,
3652 self.flags, self.Emin, self.Emax,
3653 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003654 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003655
3656 def copy(self):
3657 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003658 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003659 self.flags.copy(), self.Emin, self.Emax,
3660 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003661 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003662 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003663
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003664 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665 """Handles an error
3666
3667 If the flag is in _ignored_flags, returns the default response.
3668 Otherwise, it increments the flag, then, if the corresponding
3669 trap_enabler is set, it reaises the exception. Otherwise, it returns
3670 the default value after incrementing the flag.
3671 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003672 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003673 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003674 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003675 return error().handle(self, *args)
3676
3677 self.flags[error] += 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003678 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003679 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003680 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681
3682 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003683 # self._ignored_flags = []
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003684 raise error, explanation
3685
3686 def _ignore_all_flags(self):
3687 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003688 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003689
3690 def _ignore_flags(self, *flags):
3691 """Ignore the flags, if they are raised"""
3692 # Do not mutate-- This way, copies of a context leave the original
3693 # alone.
3694 self._ignored_flags = (self._ignored_flags + list(flags))
3695 return list(flags)
3696
3697 def _regard_flags(self, *flags):
3698 """Stop ignoring the flags, if they are raised"""
3699 if flags and isinstance(flags[0], (tuple,list)):
3700 flags = flags[0]
3701 for flag in flags:
3702 self._ignored_flags.remove(flag)
3703
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003704 def __hash__(self):
3705 """A Context cannot be hashed."""
3706 # We inherit object.__hash__, so we must deny this explicitly
Facundo Batista59c58842007-04-10 12:58:45 +00003707 raise TypeError("Cannot hash a Context.")
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003708
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709 def Etiny(self):
3710 """Returns Etiny (= Emin - prec + 1)"""
3711 return int(self.Emin - self.prec + 1)
3712
3713 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003714 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003715 return int(self.Emax - self.prec + 1)
3716
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003717 def _set_rounding(self, type):
3718 """Sets the rounding type.
3719
3720 Sets the rounding type, and returns the current (previous)
3721 rounding type. Often used like:
3722
3723 context = context.copy()
3724 # so you don't change the calling context
3725 # if an error occurs in the middle.
3726 rounding = context._set_rounding(ROUND_UP)
3727 val = self.__sub__(other, context=context)
3728 context._set_rounding(rounding)
3729
3730 This will make it round up for that operation.
3731 """
3732 rounding = self.rounding
3733 self.rounding= type
3734 return rounding
3735
Raymond Hettingerfed52962004-07-14 15:41:57 +00003736 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003737 """Creates a new Decimal instance but using self as context.
3738
3739 This method implements the to-number operation of the
3740 IBM Decimal specification."""
3741
3742 if isinstance(num, basestring) and num != num.strip():
3743 return self._raise_error(ConversionSyntax,
3744 "no trailing or leading whitespace is "
3745 "permitted.")
3746
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003747 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003748 if d._isnan() and len(d._int) > self.prec - self._clamp:
3749 return self._raise_error(ConversionSyntax,
3750 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003751 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003752
Facundo Batista59c58842007-04-10 12:58:45 +00003753 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003754 def abs(self, a):
3755 """Returns the absolute value of the operand.
3756
3757 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003758 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003759 the plus operation on the operand.
3760
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003761 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003762 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003763 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003764 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003765 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003766 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003767 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003768 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003769 """
3770 return a.__abs__(context=self)
3771
3772 def add(self, a, b):
3773 """Return the sum of the two operands.
3774
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003775 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003776 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003777 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003778 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003779 """
3780 return a.__add__(b, context=self)
3781
3782 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003783 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003784
Facundo Batista353750c2007-09-13 18:13:15 +00003785 def canonical(self, a):
3786 """Returns the same Decimal object.
3787
3788 As we do not have different encodings for the same number, the
3789 received object already is in its canonical form.
3790
3791 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003792 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003793 """
3794 return a.canonical(context=self)
3795
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003796 def compare(self, a, b):
3797 """Compares values numerically.
3798
3799 If the signs of the operands differ, a value representing each operand
3800 ('-1' if the operand is less than zero, '0' if the operand is zero or
3801 negative zero, or '1' if the operand is greater than zero) is used in
3802 place of that operand for the comparison instead of the actual
3803 operand.
3804
3805 The comparison is then effected by subtracting the second operand from
3806 the first and then returning a value according to the result of the
3807 subtraction: '-1' if the result is less than zero, '0' if the result is
3808 zero or negative zero, or '1' if the result is greater than zero.
3809
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003811 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003813 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003815 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003816 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003817 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003818 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003819 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003820 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003821 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003822 """
3823 return a.compare(b, context=self)
3824
Facundo Batista353750c2007-09-13 18:13:15 +00003825 def compare_signal(self, a, b):
3826 """Compares the values of the two operands numerically.
3827
3828 It's pretty much like compare(), but all NaNs signal, with signaling
3829 NaNs taking precedence over quiet NaNs.
3830
3831 >>> c = ExtendedContext
3832 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003833 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003834 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003835 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003836 >>> c.flags[InvalidOperation] = 0
3837 >>> print c.flags[InvalidOperation]
3838 0
3839 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003840 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003841 >>> print c.flags[InvalidOperation]
3842 1
3843 >>> c.flags[InvalidOperation] = 0
3844 >>> print c.flags[InvalidOperation]
3845 0
3846 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003847 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003848 >>> print c.flags[InvalidOperation]
3849 1
3850 """
3851 return a.compare_signal(b, context=self)
3852
3853 def compare_total(self, a, b):
3854 """Compares two operands using their abstract representation.
3855
3856 This is not like the standard compare, which use their numerical
3857 value. Note that a total ordering is defined for all possible abstract
3858 representations.
3859
3860 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003861 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003862 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003863 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003864 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003865 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003866 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003867 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003868 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003869 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003870 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003871 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003872 """
3873 return a.compare_total(b)
3874
3875 def compare_total_mag(self, a, b):
3876 """Compares two operands using their abstract representation ignoring sign.
3877
3878 Like compare_total, but with operand's sign ignored and assumed to be 0.
3879 """
3880 return a.compare_total_mag(b)
3881
3882 def copy_abs(self, a):
3883 """Returns a copy of the operand with the sign set to 0.
3884
3885 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003886 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003887 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003888 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003889 """
3890 return a.copy_abs()
3891
3892 def copy_decimal(self, a):
3893 """Returns a copy of the decimal objet.
3894
3895 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003896 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003897 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003898 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003899 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003900 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003901
3902 def copy_negate(self, a):
3903 """Returns a copy of the operand with the sign inverted.
3904
3905 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003906 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003907 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003908 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003909 """
3910 return a.copy_negate()
3911
3912 def copy_sign(self, a, b):
3913 """Copies the second operand's sign to the first one.
3914
3915 In detail, it returns a copy of the first operand with the sign
3916 equal to the sign of the second operand.
3917
3918 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003919 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003920 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003921 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003922 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003923 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003924 >>> 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 """
3927 return a.copy_sign(b)
3928
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003929 def divide(self, a, b):
3930 """Decimal division in a specified context.
3931
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003932 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003933 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003934 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003935 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003936 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003937 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003938 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003939 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003940 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003941 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003942 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003943 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003944 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003945 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003946 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003947 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003948 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003949 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003950 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003951 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003952 """
3953 return a.__div__(b, context=self)
3954
3955 def divide_int(self, a, b):
3956 """Divides two numbers and returns the integer part of the result.
3957
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003958 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003959 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003960 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003961 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003962 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003963 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003964 """
3965 return a.__floordiv__(b, context=self)
3966
3967 def divmod(self, a, b):
3968 return a.__divmod__(b, context=self)
3969
Facundo Batista353750c2007-09-13 18:13:15 +00003970 def exp(self, a):
3971 """Returns e ** a.
3972
3973 >>> c = ExtendedContext.copy()
3974 >>> c.Emin = -999
3975 >>> c.Emax = 999
3976 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003977 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003978 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003979 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00003980 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003981 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003982 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003983 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00003984 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003985 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00003986 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003987 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00003988 """
3989 return a.exp(context=self)
3990
3991 def fma(self, a, b, c):
3992 """Returns a multiplied by b, plus c.
3993
3994 The first two operands are multiplied together, using multiply,
3995 the third operand is then added to the result of that
3996 multiplication, using add, all with only one final rounding.
3997
3998 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003999 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00004000 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004001 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004002 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004003 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00004004 """
4005 return a.fma(b, c, context=self)
4006
4007 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004008 """Return True if the operand is canonical; otherwise return False.
4009
4010 Currently, the encoding of a Decimal instance is always
4011 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004012
4013 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004014 True
Facundo Batista353750c2007-09-13 18:13:15 +00004015 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004016 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004017
4018 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004019 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004020
Facundo Batista1a191df2007-10-02 17:01:24 +00004021 A Decimal instance is considered finite if it is neither
4022 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004023
4024 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004025 True
Facundo Batista353750c2007-09-13 18:13:15 +00004026 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004027 True
Facundo Batista353750c2007-09-13 18:13:15 +00004028 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004029 True
Facundo Batista353750c2007-09-13 18:13:15 +00004030 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004031 False
Facundo Batista353750c2007-09-13 18:13:15 +00004032 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004033 False
Facundo Batista353750c2007-09-13 18:13:15 +00004034 """
4035 return a.is_finite()
4036
4037 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004038 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004039
4040 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004041 False
Facundo Batista353750c2007-09-13 18:13:15 +00004042 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004043 True
Facundo Batista353750c2007-09-13 18:13:15 +00004044 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004045 False
Facundo Batista353750c2007-09-13 18:13:15 +00004046 """
4047 return a.is_infinite()
4048
4049 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004050 """Return True if the operand is a qNaN or sNaN;
4051 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004052
4053 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004054 False
Facundo Batista353750c2007-09-13 18:13:15 +00004055 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004056 True
Facundo Batista353750c2007-09-13 18:13:15 +00004057 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004058 True
Facundo Batista353750c2007-09-13 18:13:15 +00004059 """
4060 return a.is_nan()
4061
4062 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004063 """Return True if the operand is a normal number;
4064 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004065
4066 >>> c = ExtendedContext.copy()
4067 >>> c.Emin = -999
4068 >>> c.Emax = 999
4069 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004070 True
Facundo Batista353750c2007-09-13 18:13:15 +00004071 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004072 False
Facundo Batista353750c2007-09-13 18:13:15 +00004073 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004074 False
Facundo Batista353750c2007-09-13 18:13:15 +00004075 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004076 False
Facundo Batista353750c2007-09-13 18:13:15 +00004077 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004078 False
Facundo Batista353750c2007-09-13 18:13:15 +00004079 """
4080 return a.is_normal(context=self)
4081
4082 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004083 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004084
4085 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004086 False
Facundo Batista353750c2007-09-13 18:13:15 +00004087 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004088 True
Facundo Batista353750c2007-09-13 18:13:15 +00004089 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004090 False
Facundo Batista353750c2007-09-13 18:13:15 +00004091 """
4092 return a.is_qnan()
4093
4094 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004095 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004096
4097 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004098 False
Facundo Batista353750c2007-09-13 18:13:15 +00004099 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004100 True
Facundo Batista353750c2007-09-13 18:13:15 +00004101 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004102 True
Facundo Batista353750c2007-09-13 18:13:15 +00004103 """
4104 return a.is_signed()
4105
4106 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004107 """Return True if the operand is a signaling NaN;
4108 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004109
4110 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004111 False
Facundo Batista353750c2007-09-13 18:13:15 +00004112 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004113 False
Facundo Batista353750c2007-09-13 18:13:15 +00004114 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004115 True
Facundo Batista353750c2007-09-13 18:13:15 +00004116 """
4117 return a.is_snan()
4118
4119 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004120 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004121
4122 >>> c = ExtendedContext.copy()
4123 >>> c.Emin = -999
4124 >>> c.Emax = 999
4125 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004126 False
Facundo Batista353750c2007-09-13 18:13:15 +00004127 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004128 True
Facundo Batista353750c2007-09-13 18:13:15 +00004129 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004130 False
Facundo Batista353750c2007-09-13 18:13:15 +00004131 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004132 False
Facundo Batista353750c2007-09-13 18:13:15 +00004133 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004134 False
Facundo Batista353750c2007-09-13 18:13:15 +00004135 """
4136 return a.is_subnormal(context=self)
4137
4138 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004139 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004140
4141 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004142 True
Facundo Batista353750c2007-09-13 18:13:15 +00004143 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004144 False
Facundo Batista353750c2007-09-13 18:13:15 +00004145 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004146 True
Facundo Batista353750c2007-09-13 18:13:15 +00004147 """
4148 return a.is_zero()
4149
4150 def ln(self, a):
4151 """Returns the natural (base e) logarithm of the operand.
4152
4153 >>> c = ExtendedContext.copy()
4154 >>> c.Emin = -999
4155 >>> c.Emax = 999
4156 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004157 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004158 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004159 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004160 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004161 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004162 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004163 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004164 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004165 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004166 """
4167 return a.ln(context=self)
4168
4169 def log10(self, a):
4170 """Returns the base 10 logarithm of the operand.
4171
4172 >>> c = ExtendedContext.copy()
4173 >>> c.Emin = -999
4174 >>> c.Emax = 999
4175 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004176 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004177 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004178 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004179 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004180 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004181 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004182 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004183 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004184 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004185 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004186 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004187 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004188 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004189 """
4190 return a.log10(context=self)
4191
4192 def logb(self, a):
4193 """ Returns the exponent of the magnitude of the operand's MSD.
4194
4195 The result is the integer which is the exponent of the magnitude
4196 of the most significant digit of the operand (as though the
4197 operand were truncated to a single digit while maintaining the
4198 value of that digit and without limiting the resulting exponent).
4199
4200 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004201 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004202 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004203 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004204 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004205 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004206 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004207 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004208 """
4209 return a.logb(context=self)
4210
4211 def logical_and(self, a, b):
4212 """Applies the logical operation 'and' between each operand's digits.
4213
4214 The operands must be both logical numbers.
4215
4216 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004217 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004218 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004219 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004220 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004221 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004222 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004223 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004224 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004225 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004226 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004227 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004228 """
4229 return a.logical_and(b, context=self)
4230
4231 def logical_invert(self, a):
4232 """Invert all the digits in the operand.
4233
4234 The operand must be a logical number.
4235
4236 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004237 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004238 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004239 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004240 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004241 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004242 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004243 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004244 """
4245 return a.logical_invert(context=self)
4246
4247 def logical_or(self, a, b):
4248 """Applies the logical operation 'or' between each operand's digits.
4249
4250 The operands must be both logical numbers.
4251
4252 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004253 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004254 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004255 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004256 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004257 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004258 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004259 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004260 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004261 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004262 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004263 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004264 """
4265 return a.logical_or(b, context=self)
4266
4267 def logical_xor(self, a, b):
4268 """Applies the logical operation 'xor' between each operand's digits.
4269
4270 The operands must be both logical numbers.
4271
4272 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004273 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004274 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004275 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004276 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004277 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004278 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004279 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004280 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004281 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004282 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004283 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004284 """
4285 return a.logical_xor(b, context=self)
4286
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004287 def max(self, a,b):
4288 """max compares two values numerically and returns the maximum.
4289
4290 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004291 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004292 operation. If they are numerically equal then the left-hand operand
4293 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004294 infinity) of the two operands is chosen as the result.
4295
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004296 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004297 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004298 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004299 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004300 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004301 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004302 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004303 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004304 """
4305 return a.max(b, context=self)
4306
Facundo Batista353750c2007-09-13 18:13:15 +00004307 def max_mag(self, a, b):
4308 """Compares the values numerically with their sign ignored."""
4309 return a.max_mag(b, context=self)
4310
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004311 def min(self, a,b):
4312 """min compares two values numerically and returns the minimum.
4313
4314 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004315 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004316 operation. If they are numerically equal then the left-hand operand
4317 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004318 infinity) of the two operands is chosen as the result.
4319
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004320 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004321 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004322 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004323 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004324 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004325 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004326 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004327 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004328 """
4329 return a.min(b, context=self)
4330
Facundo Batista353750c2007-09-13 18:13:15 +00004331 def min_mag(self, a, b):
4332 """Compares the values numerically with their sign ignored."""
4333 return a.min_mag(b, context=self)
4334
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004335 def minus(self, a):
4336 """Minus corresponds to unary prefix minus in Python.
4337
4338 The operation is evaluated using the same rules as subtract; the
4339 operation minus(a) is calculated as subtract('0', a) where the '0'
4340 has the same exponent as the operand.
4341
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004342 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004343 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004344 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004345 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004346 """
4347 return a.__neg__(context=self)
4348
4349 def multiply(self, a, b):
4350 """multiply multiplies two operands.
4351
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004352 If either operand is a special value then the general rules apply.
4353 Otherwise, the operands are multiplied together ('long multiplication'),
4354 resulting in a number which may be as long as the sum of the lengths
4355 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004356
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004357 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004358 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004360 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004361 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004362 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004363 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004364 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004365 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004366 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004367 """
4368 return a.__mul__(b, context=self)
4369
Facundo Batista353750c2007-09-13 18:13:15 +00004370 def next_minus(self, a):
4371 """Returns the largest representable number smaller than a.
4372
4373 >>> c = ExtendedContext.copy()
4374 >>> c.Emin = -999
4375 >>> c.Emax = 999
4376 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004377 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004378 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004379 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004380 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004381 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004382 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004383 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004384 """
4385 return a.next_minus(context=self)
4386
4387 def next_plus(self, a):
4388 """Returns the smallest representable number larger than a.
4389
4390 >>> c = ExtendedContext.copy()
4391 >>> c.Emin = -999
4392 >>> c.Emax = 999
4393 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004394 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004395 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004396 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004397 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004398 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004399 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004400 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004401 """
4402 return a.next_plus(context=self)
4403
4404 def next_toward(self, a, b):
4405 """Returns the number closest to a, in direction towards b.
4406
4407 The result is the closest representable number from the first
4408 operand (but not the first operand) that is in the direction
4409 towards the second operand, unless the operands have the same
4410 value.
4411
4412 >>> c = ExtendedContext.copy()
4413 >>> c.Emin = -999
4414 >>> c.Emax = 999
4415 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004416 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004417 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004418 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004419 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004420 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004421 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004422 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004423 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
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('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004426 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004427 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004428 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004429 """
4430 return a.next_toward(b, context=self)
4431
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004432 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004433 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004434
4435 Essentially a plus operation with all trailing zeros removed from the
4436 result.
4437
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004439 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004441 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004442 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004443 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004444 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004445 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004446 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004447 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004448 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004449 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004450 """
4451 return a.normalize(context=self)
4452
Facundo Batista353750c2007-09-13 18:13:15 +00004453 def number_class(self, a):
4454 """Returns an indication of the class of the operand.
4455
4456 The class is one of the following strings:
4457 -sNaN
4458 -NaN
4459 -Infinity
4460 -Normal
4461 -Subnormal
4462 -Zero
4463 +Zero
4464 +Subnormal
4465 +Normal
4466 +Infinity
4467
4468 >>> c = Context(ExtendedContext)
4469 >>> c.Emin = -999
4470 >>> c.Emax = 999
4471 >>> c.number_class(Decimal('Infinity'))
4472 '+Infinity'
4473 >>> c.number_class(Decimal('1E-10'))
4474 '+Normal'
4475 >>> c.number_class(Decimal('2.50'))
4476 '+Normal'
4477 >>> c.number_class(Decimal('0.1E-999'))
4478 '+Subnormal'
4479 >>> c.number_class(Decimal('0'))
4480 '+Zero'
4481 >>> c.number_class(Decimal('-0'))
4482 '-Zero'
4483 >>> c.number_class(Decimal('-0.1E-999'))
4484 '-Subnormal'
4485 >>> c.number_class(Decimal('-1E-10'))
4486 '-Normal'
4487 >>> c.number_class(Decimal('-2.50'))
4488 '-Normal'
4489 >>> c.number_class(Decimal('-Infinity'))
4490 '-Infinity'
4491 >>> c.number_class(Decimal('NaN'))
4492 'NaN'
4493 >>> c.number_class(Decimal('-NaN'))
4494 'NaN'
4495 >>> c.number_class(Decimal('sNaN'))
4496 'sNaN'
4497 """
4498 return a.number_class(context=self)
4499
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004500 def plus(self, a):
4501 """Plus corresponds to unary prefix plus in Python.
4502
4503 The operation is evaluated using the same rules as add; the
4504 operation plus(a) is calculated as add('0', a) where the '0'
4505 has the same exponent as the operand.
4506
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004507 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004508 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004509 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004510 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004511 """
4512 return a.__pos__(context=self)
4513
4514 def power(self, a, b, modulo=None):
4515 """Raises a to the power of b, to modulo if given.
4516
Facundo Batista353750c2007-09-13 18:13:15 +00004517 With two arguments, compute a**b. If a is negative then b
4518 must be integral. The result will be inexact unless b is
4519 integral and the result is finite and can be expressed exactly
4520 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004521
Facundo Batista353750c2007-09-13 18:13:15 +00004522 With three arguments, compute (a**b) % modulo. For the
4523 three argument form, the following restrictions on the
4524 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004525
Facundo Batista353750c2007-09-13 18:13:15 +00004526 - all three arguments must be integral
4527 - b must be nonnegative
4528 - at least one of a or b must be nonzero
4529 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004530
Facundo Batista353750c2007-09-13 18:13:15 +00004531 The result of pow(a, b, modulo) is identical to the result
4532 that would be obtained by computing (a**b) % modulo with
4533 unbounded precision, but is computed more efficiently. It is
4534 always exact.
4535
4536 >>> c = ExtendedContext.copy()
4537 >>> c.Emin = -999
4538 >>> c.Emax = 999
4539 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004540 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004541 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004542 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004543 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004544 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004545 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004546 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004547 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004548 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004549 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004550 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004551 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004552 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004553 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004554 Decimal('Infinity')
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('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004562 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004563 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004564 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004565
4566 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004567 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004568 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004569 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004570 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004571 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004572 >>> 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('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004575 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004576 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004577 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004578 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004579 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004580 """
4581 return a.__pow__(b, modulo, context=self)
4582
4583 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004584 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004585
4586 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004587 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004588 exponent is being increased), multiplied by a positive power of ten (if
4589 the exponent is being decreased), or is unchanged (if the exponent is
4590 already equal to that of the right-hand operand).
4591
4592 Unlike other operations, if the length of the coefficient after the
4593 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004594 operation condition is raised. This guarantees that, unless there is
4595 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004596 equal to that of the right-hand operand.
4597
4598 Also unlike other operations, quantize will never raise Underflow, even
4599 if the result is subnormal and inexact.
4600
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004601 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004602 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004603 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004604 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004605 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004606 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004609 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004610 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004611 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004612 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004613 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004614 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004615 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004616 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004617 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004618 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004619 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004620 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004621 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004622 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004624 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004625 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004626 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004627 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004628 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004629 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004630 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004631 """
4632 return a.quantize(b, context=self)
4633
Facundo Batista353750c2007-09-13 18:13:15 +00004634 def radix(self):
4635 """Just returns 10, as this is Decimal, :)
4636
4637 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004638 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004639 """
4640 return Decimal(10)
4641
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004642 def remainder(self, a, b):
4643 """Returns the remainder from integer division.
4644
4645 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004646 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004647 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004648 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004649
4650 This operation will fail under the same conditions as integer division
4651 (that is, if integer division on the same two operands would fail, the
4652 remainder cannot be calculated).
4653
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004655 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004657 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004659 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004660 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004661 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004662 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004663 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004664 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004665 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004666 """
4667 return a.__mod__(b, context=self)
4668
4669 def remainder_near(self, a, b):
4670 """Returns to be "a - b * n", where n is the integer nearest the exact
4671 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004672 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004673 sign of a.
4674
4675 This operation will fail under the same conditions as integer division
4676 (that is, if integer division on the same two operands would fail, the
4677 remainder cannot be calculated).
4678
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004679 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004680 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004681 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004682 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004683 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004684 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004685 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004686 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004687 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004688 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004689 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004690 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004691 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004692 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004693 """
4694 return a.remainder_near(b, context=self)
4695
Facundo Batista353750c2007-09-13 18:13:15 +00004696 def rotate(self, a, b):
4697 """Returns a rotated copy of a, b times.
4698
4699 The coefficient of the result is a rotated copy of the digits in
4700 the coefficient of the first operand. The number of places of
4701 rotation is taken from the absolute value of the second operand,
4702 with the rotation being to the left if the second operand is
4703 positive or to the right otherwise.
4704
4705 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004706 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004707 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004708 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004709 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004710 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004711 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004712 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004713 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004714 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004715 """
4716 return a.rotate(b, context=self)
4717
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004718 def same_quantum(self, a, b):
4719 """Returns True if the two operands have the same exponent.
4720
4721 The result is never affected by either the sign or the coefficient of
4722 either operand.
4723
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004724 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004726 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004727 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004728 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004729 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004730 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004731 True
4732 """
4733 return a.same_quantum(b)
4734
Facundo Batista353750c2007-09-13 18:13:15 +00004735 def scaleb (self, a, b):
4736 """Returns the first operand after adding the second value its exp.
4737
4738 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004739 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004740 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004741 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004742 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004743 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004744 """
4745 return a.scaleb (b, context=self)
4746
4747 def shift(self, a, b):
4748 """Returns a shifted copy of a, b times.
4749
4750 The coefficient of the result is a shifted copy of the digits
4751 in the coefficient of the first operand. The number of places
4752 to shift is taken from the absolute value of the second operand,
4753 with the shift being to the left if the second operand is
4754 positive or to the right otherwise. Digits shifted into the
4755 coefficient are zeros.
4756
4757 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004758 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004759 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004760 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004761 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004762 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004763 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004764 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004765 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004766 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004767 """
4768 return a.shift(b, context=self)
4769
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004770 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004771 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004772
4773 If the result must be inexact, it is rounded using the round-half-even
4774 algorithm.
4775
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004780 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004781 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004782 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004784 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004786 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004787 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004788 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004789 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004790 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004791 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004792 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004793 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004794 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004795 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004796 """
4797 return a.sqrt(context=self)
4798
4799 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004800 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004801
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004802 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004803 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004804 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004805 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004806 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004807 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004808 """
4809 return a.__sub__(b, context=self)
4810
4811 def to_eng_string(self, a):
4812 """Converts a number to a string, using scientific notation.
4813
4814 The operation is not affected by the context.
4815 """
4816 return a.to_eng_string(context=self)
4817
4818 def to_sci_string(self, a):
4819 """Converts a number to a string, using scientific notation.
4820
4821 The operation is not affected by the context.
4822 """
4823 return a.__str__(context=self)
4824
Facundo Batista353750c2007-09-13 18:13:15 +00004825 def to_integral_exact(self, a):
4826 """Rounds to an integer.
4827
4828 When the operand has a negative exponent, the result is the same
4829 as using the quantize() operation using the given operand as the
4830 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4831 of the operand as the precision setting; Inexact and Rounded flags
4832 are allowed in this operation. The rounding mode is taken from the
4833 context.
4834
4835 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004836 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004837 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004838 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004839 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004840 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004841 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004842 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004843 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004844 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004845 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004846 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004847 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004848 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004849 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004850 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004851 """
4852 return a.to_integral_exact(context=self)
4853
4854 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004855 """Rounds to an integer.
4856
4857 When the operand has a negative exponent, the result is the same
4858 as using the quantize() operation using the given operand as the
4859 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4860 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004861 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004862
Facundo Batista353750c2007-09-13 18:13:15 +00004863 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004864 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004865 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004866 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004867 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004868 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004869 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004870 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004871 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004872 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004873 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004874 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004875 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004876 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004877 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004878 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004879 """
Facundo Batista353750c2007-09-13 18:13:15 +00004880 return a.to_integral_value(context=self)
4881
4882 # the method name changed, but we provide also the old one, for compatibility
4883 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004884
4885class _WorkRep(object):
4886 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004887 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004888 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004889 # exp: None, int, or string
4890
4891 def __init__(self, value=None):
4892 if value is None:
4893 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004894 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004895 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004896 elif isinstance(value, Decimal):
4897 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004898 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004899 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004900 else:
4901 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004902 self.sign = value[0]
4903 self.int = value[1]
4904 self.exp = value[2]
4905
4906 def __repr__(self):
4907 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4908
4909 __str__ = __repr__
4910
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004911
4912
Facundo Batistae64acfa2007-12-17 14:18:42 +00004913def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004914 """Normalizes op1, op2 to have the same exp and length of coefficient.
4915
4916 Done during addition.
4917 """
Facundo Batista353750c2007-09-13 18:13:15 +00004918 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004919 tmp = op2
4920 other = op1
4921 else:
4922 tmp = op1
4923 other = op2
4924
Facundo Batista353750c2007-09-13 18:13:15 +00004925 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4926 # Then adding 10**exp to tmp has the same effect (after rounding)
4927 # as adding any positive quantity smaller than 10**exp; similarly
4928 # for subtraction. So if other is smaller than 10**exp we replace
4929 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004930 tmp_len = len(str(tmp.int))
4931 other_len = len(str(other.int))
4932 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4933 if other_len + other.exp - 1 < exp:
4934 other.int = 1
4935 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004936
Facundo Batista353750c2007-09-13 18:13:15 +00004937 tmp.int *= 10 ** (tmp.exp - other.exp)
4938 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004939 return op1, op2
4940
Facundo Batista353750c2007-09-13 18:13:15 +00004941##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4942
4943# This function from Tim Peters was taken from here:
4944# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4945# The correction being in the function definition is for speed, and
4946# the whole function is not resolved with math.log because of avoiding
4947# the use of floats.
4948def _nbits(n, correction = {
4949 '0': 4, '1': 3, '2': 2, '3': 2,
4950 '4': 1, '5': 1, '6': 1, '7': 1,
4951 '8': 0, '9': 0, 'a': 0, 'b': 0,
4952 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4953 """Number of bits in binary representation of the positive integer n,
4954 or 0 if n == 0.
4955 """
4956 if n < 0:
4957 raise ValueError("The argument to _nbits should be nonnegative.")
4958 hex_n = "%x" % n
4959 return 4*len(hex_n) - correction[hex_n[0]]
4960
4961def _sqrt_nearest(n, a):
4962 """Closest integer to the square root of the positive integer n. a is
4963 an initial approximation to the square root. Any positive integer
4964 will do for a, but the closer a is to the square root of n the
4965 faster convergence will be.
4966
4967 """
4968 if n <= 0 or a <= 0:
4969 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4970
4971 b=0
4972 while a != b:
4973 b, a = a, a--n//a>>1
4974 return a
4975
4976def _rshift_nearest(x, shift):
4977 """Given an integer x and a nonnegative integer shift, return closest
4978 integer to x / 2**shift; use round-to-even in case of a tie.
4979
4980 """
4981 b, q = 1L << shift, x >> shift
4982 return q + (2*(x & (b-1)) + (q&1) > b)
4983
4984def _div_nearest(a, b):
4985 """Closest integer to a/b, a and b positive integers; rounds to even
4986 in the case of a tie.
4987
4988 """
4989 q, r = divmod(a, b)
4990 return q + (2*r + (q&1) > b)
4991
4992def _ilog(x, M, L = 8):
4993 """Integer approximation to M*log(x/M), with absolute error boundable
4994 in terms only of x/M.
4995
4996 Given positive integers x and M, return an integer approximation to
4997 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4998 between the approximation and the exact result is at most 22. For
4999 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5000 both cases these are upper bounds on the error; it will usually be
5001 much smaller."""
5002
5003 # The basic algorithm is the following: let log1p be the function
5004 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5005 # the reduction
5006 #
5007 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5008 #
5009 # repeatedly until the argument to log1p is small (< 2**-L in
5010 # absolute value). For small y we can use the Taylor series
5011 # expansion
5012 #
5013 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5014 #
5015 # truncating at T such that y**T is small enough. The whole
5016 # computation is carried out in a form of fixed-point arithmetic,
5017 # with a real number z being represented by an integer
5018 # approximation to z*M. To avoid loss of precision, the y below
5019 # is actually an integer approximation to 2**R*y*M, where R is the
5020 # number of reductions performed so far.
5021
5022 y = x-M
5023 # argument reduction; R = number of reductions performed
5024 R = 0
5025 while (R <= L and long(abs(y)) << L-R >= M or
5026 R > L and abs(y) >> R-L >= M):
5027 y = _div_nearest(long(M*y) << 1,
5028 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5029 R += 1
5030
5031 # Taylor series with T terms
5032 T = -int(-10*len(str(M))//(3*L))
5033 yshift = _rshift_nearest(y, R)
5034 w = _div_nearest(M, T)
5035 for k in xrange(T-1, 0, -1):
5036 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5037
5038 return _div_nearest(w*y, M)
5039
5040def _dlog10(c, e, p):
5041 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5042 approximation to 10**p * log10(c*10**e), with an absolute error of
5043 at most 1. Assumes that c*10**e is not exactly 1."""
5044
5045 # increase precision by 2; compensate for this by dividing
5046 # final result by 100
5047 p += 2
5048
5049 # write c*10**e as d*10**f with either:
5050 # f >= 0 and 1 <= d <= 10, or
5051 # f <= 0 and 0.1 <= d <= 1.
5052 # Thus for c*10**e close to 1, f = 0
5053 l = len(str(c))
5054 f = e+l - (e+l >= 1)
5055
5056 if p > 0:
5057 M = 10**p
5058 k = e+p-f
5059 if k >= 0:
5060 c *= 10**k
5061 else:
5062 c = _div_nearest(c, 10**-k)
5063
5064 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005065 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005066 log_d = _div_nearest(log_d*M, log_10)
5067 log_tenpower = f*M # exact
5068 else:
5069 log_d = 0 # error < 2.31
5070 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5071
5072 return _div_nearest(log_tenpower+log_d, 100)
5073
5074def _dlog(c, e, p):
5075 """Given integers c, e and p with c > 0, compute an integer
5076 approximation to 10**p * log(c*10**e), with an absolute error of
5077 at most 1. Assumes that c*10**e is not exactly 1."""
5078
5079 # Increase precision by 2. The precision increase is compensated
5080 # for at the end with a division by 100.
5081 p += 2
5082
5083 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5084 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5085 # as 10**p * log(d) + 10**p*f * log(10).
5086 l = len(str(c))
5087 f = e+l - (e+l >= 1)
5088
5089 # compute approximation to 10**p*log(d), with error < 27
5090 if p > 0:
5091 k = e+p-f
5092 if k >= 0:
5093 c *= 10**k
5094 else:
5095 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5096
5097 # _ilog magnifies existing error in c by a factor of at most 10
5098 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5099 else:
5100 # p <= 0: just approximate the whole thing by 0; error < 2.31
5101 log_d = 0
5102
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005103 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005104 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005105 extra = len(str(abs(f)))-1
5106 if p + extra >= 0:
5107 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5108 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5109 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005110 else:
5111 f_log_ten = 0
5112 else:
5113 f_log_ten = 0
5114
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005115 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005116 return _div_nearest(f_log_ten + log_d, 100)
5117
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005118class _Log10Memoize(object):
5119 """Class to compute, store, and allow retrieval of, digits of the
5120 constant log(10) = 2.302585.... This constant is needed by
5121 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5122 def __init__(self):
5123 self.digits = "23025850929940456840179914546843642076011014886"
5124
5125 def getdigits(self, p):
5126 """Given an integer p >= 0, return floor(10**p)*log(10).
5127
5128 For example, self.getdigits(3) returns 2302.
5129 """
5130 # digits are stored as a string, for quick conversion to
5131 # integer in the case that we've already computed enough
5132 # digits; the stored digits should always be correct
5133 # (truncated, not rounded to nearest).
5134 if p < 0:
5135 raise ValueError("p should be nonnegative")
5136
5137 if p >= len(self.digits):
5138 # compute p+3, p+6, p+9, ... digits; continue until at
5139 # least one of the extra digits is nonzero
5140 extra = 3
5141 while True:
5142 # compute p+extra digits, correct to within 1ulp
5143 M = 10**(p+extra+2)
5144 digits = str(_div_nearest(_ilog(10*M, M), 100))
5145 if digits[-extra:] != '0'*extra:
5146 break
5147 extra += 3
5148 # keep all reliable digits so far; remove trailing zeros
5149 # and next nonzero digit
5150 self.digits = digits.rstrip('0')[:-1]
5151 return int(self.digits[:p+1])
5152
5153_log10_digits = _Log10Memoize().getdigits
5154
Facundo Batista353750c2007-09-13 18:13:15 +00005155def _iexp(x, M, L=8):
5156 """Given integers x and M, M > 0, such that x/M is small in absolute
5157 value, compute an integer approximation to M*exp(x/M). For 0 <=
5158 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5159 is usually much smaller)."""
5160
5161 # Algorithm: to compute exp(z) for a real number z, first divide z
5162 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5163 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5164 # series
5165 #
5166 # expm1(x) = x + x**2/2! + x**3/3! + ...
5167 #
5168 # Now use the identity
5169 #
5170 # expm1(2x) = expm1(x)*(expm1(x)+2)
5171 #
5172 # R times to compute the sequence expm1(z/2**R),
5173 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5174
5175 # Find R such that x/2**R/M <= 2**-L
5176 R = _nbits((long(x)<<L)//M)
5177
5178 # Taylor series. (2**L)**T > M
5179 T = -int(-10*len(str(M))//(3*L))
5180 y = _div_nearest(x, T)
5181 Mshift = long(M)<<R
5182 for i in xrange(T-1, 0, -1):
5183 y = _div_nearest(x*(Mshift + y), Mshift * i)
5184
5185 # Expansion
5186 for k in xrange(R-1, -1, -1):
5187 Mshift = long(M)<<(k+2)
5188 y = _div_nearest(y*(y+Mshift), Mshift)
5189
5190 return M+y
5191
5192def _dexp(c, e, p):
5193 """Compute an approximation to exp(c*10**e), with p decimal places of
5194 precision.
5195
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005196 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005197
5198 10**(p-1) <= d <= 10**p, and
5199 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5200
5201 In other words, d*10**f is an approximation to exp(c*10**e) with p
5202 digits of precision, and with an error in d of at most 1. This is
5203 almost, but not quite, the same as the error being < 1ulp: when d
5204 = 10**(p-1) the error could be up to 10 ulp."""
5205
5206 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5207 p += 2
5208
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005209 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005210 extra = max(0, e + len(str(c)) - 1)
5211 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005212
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005213 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005214 # rounding down
5215 shift = e+q
5216 if shift >= 0:
5217 cshift = c*10**shift
5218 else:
5219 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005220 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005221
5222 # reduce remainder back to original precision
5223 rem = _div_nearest(rem, 10**extra)
5224
5225 # error in result of _iexp < 120; error after division < 0.62
5226 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5227
5228def _dpower(xc, xe, yc, ye, p):
5229 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5230 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5231
5232 10**(p-1) <= c <= 10**p, and
5233 (c-1)*10**e < x**y < (c+1)*10**e
5234
5235 in other words, c*10**e is an approximation to x**y with p digits
5236 of precision, and with an error in c of at most 1. (This is
5237 almost, but not quite, the same as the error being < 1ulp: when c
5238 == 10**(p-1) we can only guarantee error < 10ulp.)
5239
5240 We assume that: x is positive and not equal to 1, and y is nonzero.
5241 """
5242
5243 # Find b such that 10**(b-1) <= |y| <= 10**b
5244 b = len(str(abs(yc))) + ye
5245
5246 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5247 lxc = _dlog(xc, xe, p+b+1)
5248
5249 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5250 shift = ye-b
5251 if shift >= 0:
5252 pc = lxc*yc*10**shift
5253 else:
5254 pc = _div_nearest(lxc*yc, 10**-shift)
5255
5256 if pc == 0:
5257 # we prefer a result that isn't exactly 1; this makes it
5258 # easier to compute a correctly rounded result in __pow__
5259 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5260 coeff, exp = 10**(p-1)+1, 1-p
5261 else:
5262 coeff, exp = 10**p-1, -p
5263 else:
5264 coeff, exp = _dexp(pc, -(p+1), p+1)
5265 coeff = _div_nearest(coeff, 10)
5266 exp += 1
5267
5268 return coeff, exp
5269
5270def _log10_lb(c, correction = {
5271 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5272 '6': 23, '7': 16, '8': 10, '9': 5}):
5273 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5274 if c <= 0:
5275 raise ValueError("The argument to _log10_lb should be nonnegative.")
5276 str_c = str(c)
5277 return 100*len(str_c) - correction[str_c[0]]
5278
Facundo Batista59c58842007-04-10 12:58:45 +00005279##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005280
Facundo Batista353750c2007-09-13 18:13:15 +00005281def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005282 """Convert other to Decimal.
5283
5284 Verifies that it's ok to use in an implicit construction.
5285 """
5286 if isinstance(other, Decimal):
5287 return other
5288 if isinstance(other, (int, long)):
5289 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005290 if raiseit:
5291 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005292 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005293
Facundo Batista59c58842007-04-10 12:58:45 +00005294##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005295
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005296# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005297# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005298
5299DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005300 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005301 traps=[DivisionByZero, Overflow, InvalidOperation],
5302 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005303 Emax=999999999,
5304 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005305 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005306)
5307
5308# Pre-made alternate contexts offered by the specification
5309# Don't change these; the user should be able to select these
5310# contexts and be able to reproduce results from other implementations
5311# of the spec.
5312
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005313BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005314 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005315 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5316 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005317)
5318
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005319ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005320 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005321 traps=[],
5322 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005323)
5324
5325
Facundo Batista72bc54f2007-11-23 17:59:00 +00005326##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005327#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005328# Regular expression used for parsing numeric strings. Additional
5329# comments:
5330#
5331# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5332# whitespace. But note that the specification disallows whitespace in
5333# a numeric string.
5334#
5335# 2. For finite numbers (not infinities and NaNs) the body of the
5336# number between the optional sign and the optional exponent must have
5337# at least one decimal digit, possibly after the decimal point. The
5338# lookahead expression '(?=\d|\.\d)' checks this.
5339#
5340# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5341# other meaning for \d than the numbers [0-9].
5342
5343import re
5344_parser = re.compile(r""" # A numeric string consists of:
5345# \s*
5346 (?P<sign>[-+])? # an optional sign, followed by either...
5347 (
5348 (?=\d|\.\d) # ...a number (with at least one digit)
5349 (?P<int>\d*) # consisting of a (possibly empty) integer part
5350 (\.(?P<frac>\d*))? # followed by an optional fractional part
5351 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5352 |
5353 Inf(inity)? # ...an infinity, or...
5354 |
5355 (?P<signal>s)? # ...an (optionally signaling)
5356 NaN # NaN
5357 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5358 )
5359# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005360 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005361""", re.VERBOSE | re.IGNORECASE).match
5362
Facundo Batista2ec74152007-12-03 17:55:00 +00005363_all_zeros = re.compile('0*$').match
5364_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005365
5366##### PEP3101 support functions ##############################################
5367# The functions parse_format_specifier and format_align have little to do
5368# with the Decimal class, and could potentially be reused for other pure
5369# Python numeric classes that want to implement __format__
5370#
5371# A format specifier for Decimal looks like:
5372#
5373# [[fill]align][sign][0][minimumwidth][.precision][type]
5374#
5375
5376_parse_format_specifier_regex = re.compile(r"""\A
5377(?:
5378 (?P<fill>.)?
5379 (?P<align>[<>=^])
5380)?
5381(?P<sign>[-+ ])?
5382(?P<zeropad>0)?
5383(?P<minimumwidth>(?!0)\d+)?
5384(?:\.(?P<precision>0|(?!0)\d+))?
5385(?P<type>[eEfFgG%])?
5386\Z
5387""", re.VERBOSE)
5388
Facundo Batista72bc54f2007-11-23 17:59:00 +00005389del re
5390
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005391def _parse_format_specifier(format_spec):
5392 """Parse and validate a format specifier.
5393
5394 Turns a standard numeric format specifier into a dict, with the
5395 following entries:
5396
5397 fill: fill character to pad field to minimum width
5398 align: alignment type, either '<', '>', '=' or '^'
5399 sign: either '+', '-' or ' '
5400 minimumwidth: nonnegative integer giving minimum width
5401 precision: nonnegative integer giving precision, or None
5402 type: one of the characters 'eEfFgG%', or None
5403 unicode: either True or False (always True for Python 3.x)
5404
5405 """
5406 m = _parse_format_specifier_regex.match(format_spec)
5407 if m is None:
5408 raise ValueError("Invalid format specifier: " + format_spec)
5409
5410 # get the dictionary
5411 format_dict = m.groupdict()
5412
5413 # defaults for fill and alignment
5414 fill = format_dict['fill']
5415 align = format_dict['align']
5416 if format_dict.pop('zeropad') is not None:
5417 # in the face of conflict, refuse the temptation to guess
5418 if fill is not None and fill != '0':
5419 raise ValueError("Fill character conflicts with '0'"
5420 " in format specifier: " + format_spec)
5421 if align is not None and align != '=':
5422 raise ValueError("Alignment conflicts with '0' in "
5423 "format specifier: " + format_spec)
5424 fill = '0'
5425 align = '='
5426 format_dict['fill'] = fill or ' '
5427 format_dict['align'] = align or '<'
5428
5429 if format_dict['sign'] is None:
5430 format_dict['sign'] = '-'
5431
5432 # turn minimumwidth and precision entries into integers.
5433 # minimumwidth defaults to 0; precision remains None if not given
5434 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5435 if format_dict['precision'] is not None:
5436 format_dict['precision'] = int(format_dict['precision'])
5437
5438 # if format type is 'g' or 'G' then a precision of 0 makes little
5439 # sense; convert it to 1. Same if format type is unspecified.
5440 if format_dict['precision'] == 0:
5441 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5442 format_dict['precision'] = 1
5443
5444 # record whether return type should be str or unicode
5445 format_dict['unicode'] = isinstance(format_spec, unicode)
5446
5447 return format_dict
5448
5449def _format_align(body, spec_dict):
5450 """Given an unpadded, non-aligned numeric string, add padding and
5451 aligment to conform with the given format specifier dictionary (as
5452 output from parse_format_specifier).
5453
5454 It's assumed that if body is negative then it starts with '-'.
5455 Any leading sign ('-' or '+') is stripped from the body before
5456 applying the alignment and padding rules, and replaced in the
5457 appropriate position.
5458
5459 """
5460 # figure out the sign; we only examine the first character, so if
5461 # body has leading whitespace the results may be surprising.
5462 if len(body) > 0 and body[0] in '-+':
5463 sign = body[0]
5464 body = body[1:]
5465 else:
5466 sign = ''
5467
5468 if sign != '-':
5469 if spec_dict['sign'] in ' +':
5470 sign = spec_dict['sign']
5471 else:
5472 sign = ''
5473
5474 # how much extra space do we have to play with?
5475 minimumwidth = spec_dict['minimumwidth']
5476 fill = spec_dict['fill']
5477 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5478
5479 align = spec_dict['align']
5480 if align == '<':
5481 result = padding + sign + body
5482 elif align == '>':
5483 result = sign + body + padding
5484 elif align == '=':
5485 result = sign + padding + body
5486 else: #align == '^'
5487 half = len(padding)//2
5488 result = padding[:half] + sign + body + padding[half:]
5489
5490 # make sure that result is unicode if necessary
5491 if spec_dict['unicode']:
5492 result = unicode(result)
5493
5494 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005495
Facundo Batista59c58842007-04-10 12:58:45 +00005496##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005497
Facundo Batista59c58842007-04-10 12:58:45 +00005498# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005499Inf = Decimal('Inf')
5500negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005501NaN = Decimal('NaN')
5502Dec_0 = Decimal(0)
5503Dec_p1 = Decimal(1)
5504Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005505
Facundo Batista59c58842007-04-10 12:58:45 +00005506# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005507Infsign = (Inf, negInf)
5508
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005509
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005510
5511if __name__ == '__main__':
5512 import doctest, sys
5513 doctest.testmod(sys.modules[__name__])