blob: a545cf87c92250bbc45ce9299754b67049b2e40a [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
Facundo Batistaee340e52008-05-02 17:39:00 +0000480 >>> setcontext(DefaultContext)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000481 >>> print getcontext().prec
482 28
483 >>> with localcontext():
484 ... ctx = getcontext()
Raymond Hettinger495df472007-02-08 01:42:35 +0000485 ... ctx.prec += 2
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000486 ... print ctx.prec
487 ...
488 30
489 >>> with localcontext(ExtendedContext):
490 ... print getcontext().prec
491 ...
492 9
493 >>> print getcontext().prec
494 28
495 """
Nick Coghlanced12182006-09-02 03:54:17 +0000496 if ctx is None: ctx = getcontext()
497 return _ContextManager(ctx)
Nick Coghlan8b6999b2006-08-31 12:00:43 +0000498
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000499
Facundo Batista59c58842007-04-10 12:58:45 +0000500##### Decimal class #######################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000501
502class Decimal(object):
503 """Floating point class for decimal arithmetic."""
504
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000505 __slots__ = ('_exp','_int','_sign', '_is_special')
506 # Generally, the value of the Decimal instance is given by
507 # (-1)**_sign * _int * 10**_exp
508 # Special values are signified by _is_special == True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000509
Raymond Hettingerdab988d2004-10-09 07:10:44 +0000510 # We're immutable, so use __new__ not __init__
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000511 def __new__(cls, value="0", context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000512 """Create a decimal point instance.
513
514 >>> Decimal('3.14') # string input
Raymond Hettingerabe32372008-02-14 02:41:22 +0000515 Decimal('3.14')
Facundo Batista59c58842007-04-10 12:58:45 +0000516 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
Raymond Hettingerabe32372008-02-14 02:41:22 +0000517 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000518 >>> Decimal(314) # int or long
Raymond Hettingerabe32372008-02-14 02:41:22 +0000519 Decimal('314')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000520 >>> Decimal(Decimal(314)) # another decimal instance
Raymond Hettingerabe32372008-02-14 02:41:22 +0000521 Decimal('314')
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000522 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
Raymond Hettingerabe32372008-02-14 02:41:22 +0000523 Decimal('3.14')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000524 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000525
Facundo Batista72bc54f2007-11-23 17:59:00 +0000526 # Note that the coefficient, self._int, is actually stored as
527 # a string rather than as a tuple of digits. This speeds up
528 # the "digits to integer" and "integer to digits" conversions
529 # that are used in almost every arithmetic operation on
530 # Decimals. This is an internal detail: the as_tuple function
531 # and the Decimal constructor still deal with tuples of
532 # digits.
533
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000534 self = object.__new__(cls)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000535
Facundo Batista0d157a02007-11-30 17:15:25 +0000536 # From a string
537 # REs insist on real strings, so we can too.
538 if isinstance(value, basestring):
Mark Dickinson59bc20b2008-01-12 01:56:00 +0000539 m = _parser(value.strip())
Facundo Batista0d157a02007-11-30 17:15:25 +0000540 if m is None:
541 if context is None:
542 context = getcontext()
543 return context._raise_error(ConversionSyntax,
544 "Invalid literal for Decimal: %r" % value)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000545
Facundo Batista0d157a02007-11-30 17:15:25 +0000546 if m.group('sign') == "-":
547 self._sign = 1
548 else:
549 self._sign = 0
550 intpart = m.group('int')
551 if intpart is not None:
552 # finite number
553 fracpart = m.group('frac')
554 exp = int(m.group('exp') or '0')
555 if fracpart is not None:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000556 self._int = str((intpart+fracpart).lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000557 self._exp = exp - len(fracpart)
558 else:
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000559 self._int = str(intpart.lstrip('0') or '0')
Facundo Batista0d157a02007-11-30 17:15:25 +0000560 self._exp = exp
561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
Mark Dickinson8e85ffa2008-03-25 18:47:59 +0000566 self._int = str(diag.lstrip('0'))
Facundo Batista0d157a02007-11-30 17:15:25 +0000567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000576 return self
577
578 # From an integer
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000579 if isinstance(value, (int,long)):
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +0000585 self._int = str(abs(value))
Facundo Batista0d157a02007-11-30 17:15:25 +0000586 self._is_special = False
587 return self
588
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
596
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000603 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000604
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000616 self._sign = value[0]
Facundo Batista9b5e2312007-10-19 19:25:57 +0000617 if value[2] == 'F':
618 # infinity: value[1] is ignored
Facundo Batista72bc54f2007-11-23 17:59:00 +0000619 self._int = '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000620 self._exp = value[2]
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000621 self._is_special = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000622 else:
Facundo Batista9b5e2312007-10-19 19:25:57 +0000623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
Facundo Batista72bc54f2007-11-23 17:59:00 +0000636 self._int = ''.join(map(str, digits))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], (int, long)):
640 # finite number: digits give the coefficient
Facundo Batista72bc54f2007-11-23 17:59:00 +0000641 self._int = ''.join(map(str, digits or [0]))
Facundo Batista9b5e2312007-10-19 19:25:57 +0000642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000648 return self
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000649
Raymond Hettingerbf440692004-07-10 14:14:37 +0000650 if isinstance(value, float):
651 raise TypeError("Cannot convert float to Decimal. " +
652 "First convert the float to a string")
653
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000654 raise TypeError("Cannot convert %r to Decimal" % value)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000655
656 def _isnan(self):
657 """Returns whether the number is not actually one.
658
659 0 if a number
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000660 1 if NaN
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000661 2 if sNaN
662 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000663 if self._is_special:
664 exp = self._exp
665 if exp == 'n':
666 return 1
667 elif exp == 'N':
668 return 2
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000669 return 0
670
671 def _isinfinity(self):
672 """Returns whether the number is infinite
673
674 0 if finite or not a number
675 1 if +INF
676 -1 if -INF
677 """
678 if self._exp == 'F':
679 if self._sign:
680 return -1
681 return 1
682 return 0
683
Facundo Batista353750c2007-09-13 18:13:15 +0000684 def _check_nans(self, other=None, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000685 """Returns whether the number is not actually one.
686
687 if self, other are sNaN, signal
688 if self, other are NaN return nan
689 return 0
690
691 Done before operations.
692 """
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000693
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000694 self_is_nan = self._isnan()
695 if other is None:
696 other_is_nan = False
697 else:
698 other_is_nan = other._isnan()
699
700 if self_is_nan or other_is_nan:
701 if context is None:
702 context = getcontext()
703
704 if self_is_nan == 2:
705 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000706 self)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000707 if other_is_nan == 2:
708 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000709 other)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000710 if self_is_nan:
Facundo Batista353750c2007-09-13 18:13:15 +0000711 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000712
Facundo Batista353750c2007-09-13 18:13:15 +0000713 return other._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000714 return 0
715
Mark Dickinson2fc92632008-02-06 22:10:50 +0000716 def _compare_check_nans(self, other, context):
717 """Version of _check_nans used for the signaling comparisons
718 compare_signal, __le__, __lt__, __ge__, __gt__.
719
720 Signal InvalidOperation if either self or other is a (quiet
721 or signaling) NaN. Signaling NaNs take precedence over quiet
722 NaNs.
723
724 Return 0 if neither operand is a NaN.
725
726 """
727 if context is None:
728 context = getcontext()
729
730 if self._is_special or other._is_special:
731 if self.is_snan():
732 return context._raise_error(InvalidOperation,
733 'comparison involving sNaN',
734 self)
735 elif other.is_snan():
736 return context._raise_error(InvalidOperation,
737 'comparison involving sNaN',
738 other)
739 elif self.is_qnan():
740 return context._raise_error(InvalidOperation,
741 'comparison involving NaN',
742 self)
743 elif other.is_qnan():
744 return context._raise_error(InvalidOperation,
745 'comparison involving NaN',
746 other)
747 return 0
748
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000749 def __nonzero__(self):
Facundo Batista1a191df2007-10-02 17:01:24 +0000750 """Return True if self is nonzero; otherwise return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000751
Facundo Batista1a191df2007-10-02 17:01:24 +0000752 NaNs and infinities are considered nonzero.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000753 """
Facundo Batista72bc54f2007-11-23 17:59:00 +0000754 return self._is_special or self._int != '0'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000755
Mark Dickinson2fc92632008-02-06 22:10:50 +0000756 def _cmp(self, other):
757 """Compare the two non-NaN decimal instances self and other.
758
759 Returns -1 if self < other, 0 if self == other and 1
760 if self > other. This routine is for internal use only."""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000761
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000762 if self._is_special or other._is_special:
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000763 return cmp(self._isinfinity(), other._isinfinity())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000764
Facundo Batista353750c2007-09-13 18:13:15 +0000765 # check for zeros; note that cmp(0, -0) should return 0
766 if not self:
767 if not other:
768 return 0
769 else:
770 return -((-1)**other._sign)
771 if not other:
772 return (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000773
Facundo Batista59c58842007-04-10 12:58:45 +0000774 # If different signs, neg one is less
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000775 if other._sign < self._sign:
776 return -1
777 if self._sign < other._sign:
778 return 1
779
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000780 self_adjusted = self.adjusted()
781 other_adjusted = other.adjusted()
Facundo Batista353750c2007-09-13 18:13:15 +0000782 if self_adjusted == other_adjusted:
Facundo Batista72bc54f2007-11-23 17:59:00 +0000783 self_padded = self._int + '0'*(self._exp - other._exp)
784 other_padded = other._int + '0'*(other._exp - self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +0000785 return cmp(self_padded, other_padded) * (-1)**self._sign
786 elif self_adjusted > other_adjusted:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000787 return (-1)**self._sign
Facundo Batista353750c2007-09-13 18:13:15 +0000788 else: # self_adjusted < other_adjusted
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000789 return -((-1)**self._sign)
790
Mark Dickinson2fc92632008-02-06 22:10:50 +0000791 # Note: The Decimal standard doesn't cover rich comparisons for
792 # Decimals. In particular, the specification is silent on the
793 # subject of what should happen for a comparison involving a NaN.
794 # We take the following approach:
795 #
796 # == comparisons involving a NaN always return False
797 # != comparisons involving a NaN always return True
798 # <, >, <= and >= comparisons involving a (quiet or signaling)
799 # NaN signal InvalidOperation, and return False if the
Mark Dickinson3a94ee02008-02-10 15:19:58 +0000800 # InvalidOperation is not trapped.
Mark Dickinson2fc92632008-02-06 22:10:50 +0000801 #
802 # This behavior is designed to conform as closely as possible to
803 # that specified by IEEE 754.
804
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000805 def __eq__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000806 other = _convert_other(other)
807 if other is NotImplemented:
808 return other
809 if self.is_nan() or other.is_nan():
810 return False
811 return self._cmp(other) == 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000812
813 def __ne__(self, other):
Mark Dickinson2fc92632008-02-06 22:10:50 +0000814 other = _convert_other(other)
815 if other is NotImplemented:
816 return other
817 if self.is_nan() or other.is_nan():
818 return True
819 return self._cmp(other) != 0
820
821 def __lt__(self, other, context=None):
822 other = _convert_other(other)
823 if other is NotImplemented:
824 return other
825 ans = self._compare_check_nans(other, context)
826 if ans:
827 return False
828 return self._cmp(other) < 0
829
830 def __le__(self, other, context=None):
831 other = _convert_other(other)
832 if other is NotImplemented:
833 return other
834 ans = self._compare_check_nans(other, context)
835 if ans:
836 return False
837 return self._cmp(other) <= 0
838
839 def __gt__(self, other, context=None):
840 other = _convert_other(other)
841 if other is NotImplemented:
842 return other
843 ans = self._compare_check_nans(other, context)
844 if ans:
845 return False
846 return self._cmp(other) > 0
847
848 def __ge__(self, other, context=None):
849 other = _convert_other(other)
850 if other is NotImplemented:
851 return other
852 ans = self._compare_check_nans(other, context)
853 if ans:
854 return False
855 return self._cmp(other) >= 0
Raymond Hettinger0aeac102004-07-05 22:53:03 +0000856
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000857 def compare(self, other, context=None):
858 """Compares one to another.
859
860 -1 => a < b
861 0 => a = b
862 1 => a > b
863 NaN => one is NaN
864 Like __cmp__, but returns Decimal instances.
865 """
Facundo Batista353750c2007-09-13 18:13:15 +0000866 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000867
Facundo Batista59c58842007-04-10 12:58:45 +0000868 # Compare(NaN, NaN) = NaN
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000869 if (self._is_special or other and other._is_special):
870 ans = self._check_nans(other, context)
871 if ans:
872 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000873
Mark Dickinson2fc92632008-02-06 22:10:50 +0000874 return Decimal(self._cmp(other))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000875
876 def __hash__(self):
877 """x.__hash__() <==> hash(x)"""
878 # Decimal integers must hash the same as the ints
Facundo Batista52b25792008-01-08 12:25:20 +0000879 #
880 # The hash of a nonspecial noninteger Decimal must depend only
881 # on the value of that Decimal, and not on its representation.
Raymond Hettingerabe32372008-02-14 02:41:22 +0000882 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
Raymond Hettingerbea3f6f2005-03-15 04:59:17 +0000883 if self._is_special:
884 if self._isnan():
885 raise TypeError('Cannot hash a NaN value.')
886 return hash(str(self))
Facundo Batista8c202442007-09-19 17:53:25 +0000887 if not self:
888 return 0
889 if self._isinteger():
890 op = _WorkRep(self.to_integral_value())
891 # to make computation feasible for Decimals with large
892 # exponent, we use the fact that hash(n) == hash(m) for
893 # any two nonzero integers n and m such that (i) n and m
894 # have the same sign, and (ii) n is congruent to m modulo
895 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
896 # hash((-1)**s*c*pow(10, e, 2**64-1).
897 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
Facundo Batista52b25792008-01-08 12:25:20 +0000898 # The value of a nonzero nonspecial Decimal instance is
899 # faithfully represented by the triple consisting of its sign,
900 # its adjusted exponent, and its coefficient with trailing
901 # zeros removed.
902 return hash((self._sign,
903 self._exp+len(self._int),
904 self._int.rstrip('0')))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000905
906 def as_tuple(self):
907 """Represents the number as a triple tuple.
908
909 To show the internals exactly as they are.
910 """
Raymond Hettinger097a1902008-01-11 02:24:13 +0000911 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000912
913 def __repr__(self):
914 """Represents the number as an instance of Decimal."""
915 # Invariant: eval(repr(d)) == d
Raymond Hettingerabe32372008-02-14 02:41:22 +0000916 return "Decimal('%s')" % str(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000917
Facundo Batista353750c2007-09-13 18:13:15 +0000918 def __str__(self, eng=False, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000919 """Return string representation of the number in scientific notation.
920
921 Captures all of the information in the underlying representation.
922 """
923
Facundo Batista62edb712007-12-03 16:29:52 +0000924 sign = ['', '-'][self._sign]
Raymond Hettingere5a0a962005-06-20 09:49:42 +0000925 if self._is_special:
Facundo Batista62edb712007-12-03 16:29:52 +0000926 if self._exp == 'F':
927 return sign + 'Infinity'
928 elif self._exp == 'n':
929 return sign + 'NaN' + self._int
930 else: # self._exp == 'N'
931 return sign + 'sNaN' + self._int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000932
Facundo Batista62edb712007-12-03 16:29:52 +0000933 # number of digits of self._int to left of decimal point
934 leftdigits = self._exp + len(self._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000935
Facundo Batista62edb712007-12-03 16:29:52 +0000936 # dotplace is number of digits of self._int to the left of the
937 # decimal point in the mantissa of the output string (that is,
938 # after adjusting the exponent)
939 if self._exp <= 0 and leftdigits > -6:
940 # no exponent required
941 dotplace = leftdigits
942 elif not eng:
943 # usual scientific notation: 1 digit on left of the point
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000944 dotplace = 1
Facundo Batista62edb712007-12-03 16:29:52 +0000945 elif self._int == '0':
946 # engineering notation, zero
947 dotplace = (leftdigits + 1) % 3 - 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000948 else:
Facundo Batista62edb712007-12-03 16:29:52 +0000949 # engineering notation, nonzero
950 dotplace = (leftdigits - 1) % 3 + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000951
Facundo Batista62edb712007-12-03 16:29:52 +0000952 if dotplace <= 0:
953 intpart = '0'
954 fracpart = '.' + '0'*(-dotplace) + self._int
955 elif dotplace >= len(self._int):
956 intpart = self._int+'0'*(dotplace-len(self._int))
957 fracpart = ''
958 else:
959 intpart = self._int[:dotplace]
960 fracpart = '.' + self._int[dotplace:]
961 if leftdigits == dotplace:
962 exp = ''
963 else:
964 if context is None:
965 context = getcontext()
966 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
967
968 return sign + intpart + fracpart + exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000969
970 def to_eng_string(self, context=None):
971 """Convert to engineering-type string.
972
973 Engineering notation has an exponent which is a multiple of 3, so there
974 are up to 3 digits left of the decimal place.
975
976 Same rules for when in exponential and when as a value as in __str__.
977 """
Facundo Batista353750c2007-09-13 18:13:15 +0000978 return self.__str__(eng=True, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000979
980 def __neg__(self, context=None):
981 """Returns a copy with the sign switched.
982
983 Rounds, if it has reason.
984 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000985 if self._is_special:
986 ans = self._check_nans(context=context)
987 if ans:
988 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000989
990 if not self:
991 # -Decimal('0') is Decimal('0'), not Decimal('-0')
Facundo Batista0f5e7bf2007-12-19 12:53:01 +0000992 ans = self.copy_abs()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000993 else:
Facundo Batista353750c2007-09-13 18:13:15 +0000994 ans = self.copy_negate()
Raymond Hettinger636a6b12004-09-19 01:54:09 +0000995
996 if context is None:
997 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +0000998 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +0000999
1000 def __pos__(self, context=None):
1001 """Returns a copy, unless it is a sNaN.
1002
1003 Rounds the number (if more then precision digits)
1004 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001005 if self._is_special:
1006 ans = self._check_nans(context=context)
1007 if ans:
1008 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001009
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001010 if not self:
1011 # + (-0) = 0
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001012 ans = self.copy_abs()
Facundo Batista353750c2007-09-13 18:13:15 +00001013 else:
1014 ans = Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001015
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001016 if context is None:
1017 context = getcontext()
Facundo Batistae64acfa2007-12-17 14:18:42 +00001018 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001019
Facundo Batistae64acfa2007-12-17 14:18:42 +00001020 def __abs__(self, round=True, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001021 """Returns the absolute value of self.
1022
Facundo Batistae64acfa2007-12-17 14:18:42 +00001023 If the keyword argument 'round' is false, do not round. The
1024 expression self.__abs__(round=False) is equivalent to
1025 self.copy_abs().
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001026 """
Facundo Batistae64acfa2007-12-17 14:18:42 +00001027 if not round:
1028 return self.copy_abs()
1029
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001030 if self._is_special:
1031 ans = self._check_nans(context=context)
1032 if ans:
1033 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001034
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001035 if self._sign:
1036 ans = self.__neg__(context=context)
1037 else:
1038 ans = self.__pos__(context=context)
1039
1040 return ans
1041
1042 def __add__(self, other, context=None):
1043 """Returns self + other.
1044
1045 -INF + INF (or the reverse) cause InvalidOperation errors.
1046 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001047 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001048 if other is NotImplemented:
1049 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001050
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001051 if context is None:
1052 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001053
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001054 if self._is_special or other._is_special:
1055 ans = self._check_nans(other, context)
1056 if ans:
1057 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001058
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001059 if self._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001060 # If both INF, same sign => same as both, opposite => error.
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001061 if self._sign != other._sign and other._isinfinity():
1062 return context._raise_error(InvalidOperation, '-INF + INF')
1063 return Decimal(self)
1064 if other._isinfinity():
Facundo Batista59c58842007-04-10 12:58:45 +00001065 return Decimal(other) # Can't both be infinity here
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001066
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001067 exp = min(self._exp, other._exp)
1068 negativezero = 0
1069 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
Facundo Batista59c58842007-04-10 12:58:45 +00001070 # If the answer is 0, the sign should be negative, in this case.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001071 negativezero = 1
1072
1073 if not self and not other:
1074 sign = min(self._sign, other._sign)
1075 if negativezero:
1076 sign = 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00001077 ans = _dec_from_triple(sign, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001078 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001079 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001080 if not self:
Facundo Batista99b55482004-10-26 23:38:46 +00001081 exp = max(exp, other._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001082 ans = other._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001083 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001084 return ans
1085 if not other:
Facundo Batista99b55482004-10-26 23:38:46 +00001086 exp = max(exp, self._exp - context.prec-1)
Facundo Batista353750c2007-09-13 18:13:15 +00001087 ans = self._rescale(exp, context.rounding)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001088 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001089 return ans
1090
1091 op1 = _WorkRep(self)
1092 op2 = _WorkRep(other)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001093 op1, op2 = _normalize(op1, op2, context.prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001094
1095 result = _WorkRep()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001096 if op1.sign != op2.sign:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001097 # Equal and opposite
Raymond Hettinger17931de2004-10-27 06:21:46 +00001098 if op1.int == op2.int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001099 ans = _dec_from_triple(negativezero, '0', exp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001100 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001101 return ans
Raymond Hettinger17931de2004-10-27 06:21:46 +00001102 if op1.int < op2.int:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001103 op1, op2 = op2, op1
Facundo Batista59c58842007-04-10 12:58:45 +00001104 # OK, now abs(op1) > abs(op2)
Raymond Hettinger17931de2004-10-27 06:21:46 +00001105 if op1.sign == 1:
1106 result.sign = 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001107 op1.sign, op2.sign = op2.sign, op1.sign
1108 else:
Raymond Hettinger17931de2004-10-27 06:21:46 +00001109 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001110 # So we know the sign, and op1 > 0.
Raymond Hettinger17931de2004-10-27 06:21:46 +00001111 elif op1.sign == 1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001112 result.sign = 1
Raymond Hettinger17931de2004-10-27 06:21:46 +00001113 op1.sign, op2.sign = (0, 0)
1114 else:
1115 result.sign = 0
Facundo Batista59c58842007-04-10 12:58:45 +00001116 # Now, op1 > abs(op2) > 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001117
Raymond Hettinger17931de2004-10-27 06:21:46 +00001118 if op2.sign == 0:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001119 result.int = op1.int + op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001120 else:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001121 result.int = op1.int - op2.int
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001122
1123 result.exp = op1.exp
1124 ans = Decimal(result)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001125 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001126 return ans
1127
1128 __radd__ = __add__
1129
1130 def __sub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001131 """Return self - other"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001132 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001133 if other is NotImplemented:
1134 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001135
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001136 if self._is_special or other._is_special:
1137 ans = self._check_nans(other, context=context)
1138 if ans:
1139 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001140
Facundo Batista353750c2007-09-13 18:13:15 +00001141 # self - other is computed as self + other.copy_negate()
1142 return self.__add__(other.copy_negate(), context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001143
1144 def __rsub__(self, other, context=None):
Facundo Batista353750c2007-09-13 18:13:15 +00001145 """Return other - self"""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001146 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001147 if other is NotImplemented:
1148 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001149
Facundo Batista353750c2007-09-13 18:13:15 +00001150 return other.__sub__(self, context=context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001151
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001152 def __mul__(self, other, context=None):
1153 """Return self * other.
1154
1155 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1156 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001157 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001158 if other is NotImplemented:
1159 return other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001160
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001161 if context is None:
1162 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001163
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001164 resultsign = self._sign ^ other._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001165
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001166 if self._is_special or other._is_special:
1167 ans = self._check_nans(other, context)
1168 if ans:
1169 return ans
1170
1171 if self._isinfinity():
1172 if not other:
1173 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1174 return Infsign[resultsign]
1175
1176 if other._isinfinity():
1177 if not self:
1178 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1179 return Infsign[resultsign]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001180
1181 resultexp = self._exp + other._exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001182
1183 # Special case for multiplying by zero
1184 if not self or not other:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001185 ans = _dec_from_triple(resultsign, '0', resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001186 # Fixing in case the exponent is out of bounds
1187 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001188 return ans
1189
1190 # Special case for multiplying by power of 10
Facundo Batista72bc54f2007-11-23 17:59:00 +00001191 if self._int == '1':
1192 ans = _dec_from_triple(resultsign, other._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001193 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001194 return ans
Facundo Batista72bc54f2007-11-23 17:59:00 +00001195 if other._int == '1':
1196 ans = _dec_from_triple(resultsign, self._int, resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001197 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001198 return ans
1199
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001200 op1 = _WorkRep(self)
1201 op2 = _WorkRep(other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001202
Facundo Batista72bc54f2007-11-23 17:59:00 +00001203 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001204 ans = ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001205
1206 return ans
1207 __rmul__ = __mul__
1208
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001209 def __truediv__(self, other, context=None):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001210 """Return self / other."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001211 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001212 if other is NotImplemented:
Facundo Batistacce8df22007-09-18 16:53:18 +00001213 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001214
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001215 if context is None:
1216 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001217
Raymond Hettingerd87ac8f2004-07-09 10:52:54 +00001218 sign = self._sign ^ other._sign
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001219
1220 if self._is_special or other._is_special:
1221 ans = self._check_nans(other, context)
1222 if ans:
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001223 return ans
1224
1225 if self._isinfinity() and other._isinfinity():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001226 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001227
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001228 if self._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001229 return Infsign[sign]
1230
1231 if other._isinfinity():
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001232 context._raise_error(Clamped, 'Division by infinity')
Facundo Batista72bc54f2007-11-23 17:59:00 +00001233 return _dec_from_triple(sign, '0', context.Etiny())
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001234
1235 # Special cases for zeroes
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001236 if not other:
Facundo Batistacce8df22007-09-18 16:53:18 +00001237 if not self:
1238 return context._raise_error(DivisionUndefined, '0 / 0')
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001239 return context._raise_error(DivisionByZero, 'x / 0', sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001240
Facundo Batistacce8df22007-09-18 16:53:18 +00001241 if not self:
1242 exp = self._exp - other._exp
1243 coeff = 0
1244 else:
1245 # OK, so neither = 0, INF or NaN
1246 shift = len(other._int) - len(self._int) + context.prec + 1
1247 exp = self._exp - other._exp - shift
1248 op1 = _WorkRep(self)
1249 op2 = _WorkRep(other)
1250 if shift >= 0:
1251 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1252 else:
1253 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1254 if remainder:
1255 # result is not exact; adjust to ensure correct rounding
1256 if coeff % 5 == 0:
1257 coeff += 1
1258 else:
1259 # result is exact; get as close to ideal exponent as possible
1260 ideal_exp = self._exp - other._exp
1261 while exp < ideal_exp and coeff % 10 == 0:
1262 coeff //= 10
1263 exp += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001264
Facundo Batista72bc54f2007-11-23 17:59:00 +00001265 ans = _dec_from_triple(sign, str(coeff), exp)
Facundo Batistacce8df22007-09-18 16:53:18 +00001266 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001267
Facundo Batistacce8df22007-09-18 16:53:18 +00001268 def _divide(self, other, context):
1269 """Return (self // other, self % other), to context.prec precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001270
Facundo Batistacce8df22007-09-18 16:53:18 +00001271 Assumes that neither self nor other is a NaN, that self is not
1272 infinite and that other is nonzero.
1273 """
1274 sign = self._sign ^ other._sign
1275 if other._isinfinity():
1276 ideal_exp = self._exp
1277 else:
1278 ideal_exp = min(self._exp, other._exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001279
Facundo Batistacce8df22007-09-18 16:53:18 +00001280 expdiff = self.adjusted() - other.adjusted()
1281 if not self or other._isinfinity() or expdiff <= -2:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001282 return (_dec_from_triple(sign, '0', 0),
Facundo Batistacce8df22007-09-18 16:53:18 +00001283 self._rescale(ideal_exp, context.rounding))
1284 if expdiff <= context.prec:
1285 op1 = _WorkRep(self)
1286 op2 = _WorkRep(other)
1287 if op1.exp >= op2.exp:
1288 op1.int *= 10**(op1.exp - op2.exp)
1289 else:
1290 op2.int *= 10**(op2.exp - op1.exp)
1291 q, r = divmod(op1.int, op2.int)
1292 if q < 10**context.prec:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001293 return (_dec_from_triple(sign, str(q), 0),
1294 _dec_from_triple(self._sign, str(r), ideal_exp))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001295
Facundo Batistacce8df22007-09-18 16:53:18 +00001296 # Here the quotient is too large to be representable
1297 ans = context._raise_error(DivisionImpossible,
1298 'quotient too large in //, % or divmod')
1299 return ans, ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001300
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001301 def __rtruediv__(self, other, context=None):
1302 """Swaps self/other and returns __truediv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001303 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001304 if other is NotImplemented:
1305 return other
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001306 return other.__truediv__(self, context=context)
1307
1308 __div__ = __truediv__
1309 __rdiv__ = __rtruediv__
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001310
1311 def __divmod__(self, other, context=None):
1312 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001313 Return (self // other, self % other)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001314 """
Facundo Batistacce8df22007-09-18 16:53:18 +00001315 other = _convert_other(other)
1316 if other is NotImplemented:
1317 return other
1318
1319 if context is None:
1320 context = getcontext()
1321
1322 ans = self._check_nans(other, context)
1323 if ans:
1324 return (ans, ans)
1325
1326 sign = self._sign ^ other._sign
1327 if self._isinfinity():
1328 if other._isinfinity():
1329 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1330 return ans, ans
1331 else:
1332 return (Infsign[sign],
1333 context._raise_error(InvalidOperation, 'INF % x'))
1334
1335 if not other:
1336 if not self:
1337 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1338 return ans, ans
1339 else:
1340 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1341 context._raise_error(InvalidOperation, 'x % 0'))
1342
1343 quotient, remainder = self._divide(other, context)
Facundo Batistae64acfa2007-12-17 14:18:42 +00001344 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001345 return quotient, remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001346
1347 def __rdivmod__(self, other, context=None):
1348 """Swaps self/other and returns __divmod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001349 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001350 if other is NotImplemented:
1351 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001352 return other.__divmod__(self, context=context)
1353
1354 def __mod__(self, other, context=None):
1355 """
1356 self % other
1357 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001358 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001359 if other is NotImplemented:
1360 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001361
Facundo Batistacce8df22007-09-18 16:53:18 +00001362 if context is None:
1363 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001364
Facundo Batistacce8df22007-09-18 16:53:18 +00001365 ans = self._check_nans(other, context)
1366 if ans:
1367 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001368
Facundo Batistacce8df22007-09-18 16:53:18 +00001369 if self._isinfinity():
1370 return context._raise_error(InvalidOperation, 'INF % x')
1371 elif not other:
1372 if self:
1373 return context._raise_error(InvalidOperation, 'x % 0')
1374 else:
1375 return context._raise_error(DivisionUndefined, '0 % 0')
1376
1377 remainder = self._divide(other, context)[1]
Facundo Batistae64acfa2007-12-17 14:18:42 +00001378 remainder = remainder._fix(context)
Facundo Batistacce8df22007-09-18 16:53:18 +00001379 return remainder
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001380
1381 def __rmod__(self, other, context=None):
1382 """Swaps self/other and returns __mod__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001383 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001384 if other is NotImplemented:
1385 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001386 return other.__mod__(self, context=context)
1387
1388 def remainder_near(self, other, context=None):
1389 """
1390 Remainder nearest to 0- abs(remainder-near) <= other/2
1391 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001392 if context is None:
1393 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001394
Facundo Batista353750c2007-09-13 18:13:15 +00001395 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001396
Facundo Batista353750c2007-09-13 18:13:15 +00001397 ans = self._check_nans(other, context)
1398 if ans:
1399 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001400
Facundo Batista353750c2007-09-13 18:13:15 +00001401 # self == +/-infinity -> InvalidOperation
1402 if self._isinfinity():
1403 return context._raise_error(InvalidOperation,
1404 'remainder_near(infinity, x)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001405
Facundo Batista353750c2007-09-13 18:13:15 +00001406 # other == 0 -> either InvalidOperation or DivisionUndefined
1407 if not other:
1408 if self:
1409 return context._raise_error(InvalidOperation,
1410 'remainder_near(x, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001411 else:
Facundo Batista353750c2007-09-13 18:13:15 +00001412 return context._raise_error(DivisionUndefined,
1413 'remainder_near(0, 0)')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001414
Facundo Batista353750c2007-09-13 18:13:15 +00001415 # other = +/-infinity -> remainder = self
1416 if other._isinfinity():
1417 ans = Decimal(self)
1418 return ans._fix(context)
1419
1420 # self = 0 -> remainder = self, with ideal exponent
1421 ideal_exponent = min(self._exp, other._exp)
1422 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001423 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001424 return ans._fix(context)
1425
1426 # catch most cases of large or small quotient
1427 expdiff = self.adjusted() - other.adjusted()
1428 if expdiff >= context.prec + 1:
1429 # expdiff >= prec+1 => abs(self/other) > 10**prec
Facundo Batistacce8df22007-09-18 16:53:18 +00001430 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001431 if expdiff <= -2:
1432 # expdiff <= -2 => abs(self/other) < 0.1
1433 ans = self._rescale(ideal_exponent, context.rounding)
1434 return ans._fix(context)
1435
1436 # adjust both arguments to have the same exponent, then divide
1437 op1 = _WorkRep(self)
1438 op2 = _WorkRep(other)
1439 if op1.exp >= op2.exp:
1440 op1.int *= 10**(op1.exp - op2.exp)
1441 else:
1442 op2.int *= 10**(op2.exp - op1.exp)
1443 q, r = divmod(op1.int, op2.int)
1444 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1445 # 10**ideal_exponent. Apply correction to ensure that
1446 # abs(remainder) <= abs(other)/2
1447 if 2*r + (q&1) > op2.int:
1448 r -= op2.int
1449 q += 1
1450
1451 if q >= 10**context.prec:
Facundo Batistacce8df22007-09-18 16:53:18 +00001452 return context._raise_error(DivisionImpossible)
Facundo Batista353750c2007-09-13 18:13:15 +00001453
1454 # result has same sign as self unless r is negative
1455 sign = self._sign
1456 if r < 0:
1457 sign = 1-sign
1458 r = -r
1459
Facundo Batista72bc54f2007-11-23 17:59:00 +00001460 ans = _dec_from_triple(sign, str(r), ideal_exponent)
Facundo Batista353750c2007-09-13 18:13:15 +00001461 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001462
1463 def __floordiv__(self, other, context=None):
1464 """self // other"""
Facundo Batistacce8df22007-09-18 16:53:18 +00001465 other = _convert_other(other)
1466 if other is NotImplemented:
1467 return other
1468
1469 if context is None:
1470 context = getcontext()
1471
1472 ans = self._check_nans(other, context)
1473 if ans:
1474 return ans
1475
1476 if self._isinfinity():
1477 if other._isinfinity():
1478 return context._raise_error(InvalidOperation, 'INF // INF')
1479 else:
1480 return Infsign[self._sign ^ other._sign]
1481
1482 if not other:
1483 if self:
1484 return context._raise_error(DivisionByZero, 'x // 0',
1485 self._sign ^ other._sign)
1486 else:
1487 return context._raise_error(DivisionUndefined, '0 // 0')
1488
1489 return self._divide(other, context)[0]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001490
1491 def __rfloordiv__(self, other, context=None):
1492 """Swaps self/other and returns __floordiv__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001493 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00001494 if other is NotImplemented:
1495 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001496 return other.__floordiv__(self, context=context)
1497
1498 def __float__(self):
1499 """Float representation."""
1500 return float(str(self))
1501
1502 def __int__(self):
Brett Cannon46b08022005-03-01 03:12:26 +00001503 """Converts self to an int, truncating if necessary."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001504 if self._is_special:
1505 if self._isnan():
1506 context = getcontext()
1507 return context._raise_error(InvalidContext)
1508 elif self._isinfinity():
Mark Dickinson8aca9d02008-05-04 02:05:06 +00001509 raise OverflowError("Cannot convert infinity to int")
Facundo Batista353750c2007-09-13 18:13:15 +00001510 s = (-1)**self._sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001511 if self._exp >= 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001512 return s*int(self._int)*10**self._exp
Raymond Hettinger605ed022004-11-24 07:28:48 +00001513 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001514 return s*int(self._int[:self._exp] or '0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001515
Raymond Hettinger5a053642008-01-24 19:05:29 +00001516 __trunc__ = __int__
1517
Raymond Hettinger116f72f2008-02-12 01:18:03 +00001518 @property
1519 def real(self):
1520 return self
1521
1522 @property
1523 def imag(self):
1524 return Decimal(0)
1525
1526 def conjugate(self):
1527 return self
1528
1529 def __complex__(self):
1530 return complex(float(self))
1531
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001532 def __long__(self):
1533 """Converts to a long.
1534
1535 Equivalent to long(int(self))
1536 """
1537 return long(self.__int__())
1538
Facundo Batista353750c2007-09-13 18:13:15 +00001539 def _fix_nan(self, context):
1540 """Decapitate the payload of a NaN to fit the context"""
1541 payload = self._int
1542
1543 # maximum length of payload is precision if _clamp=0,
1544 # precision-1 if _clamp=1.
1545 max_payload_len = context.prec - context._clamp
1546 if len(payload) > max_payload_len:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001547 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1548 return _dec_from_triple(self._sign, payload, self._exp, True)
Facundo Batista6c398da2007-09-17 17:30:13 +00001549 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001550
Raymond Hettingerdab988d2004-10-09 07:10:44 +00001551 def _fix(self, context):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001552 """Round if it is necessary to keep self within prec precision.
1553
1554 Rounds and fixes the exponent. Does not raise on a sNaN.
1555
1556 Arguments:
1557 self - Decimal instance
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001558 context - context used.
1559 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00001560
Facundo Batista353750c2007-09-13 18:13:15 +00001561 if self._is_special:
1562 if self._isnan():
1563 # decapitate payload if necessary
1564 return self._fix_nan(context)
1565 else:
1566 # self is +/-Infinity; return unaltered
Facundo Batista6c398da2007-09-17 17:30:13 +00001567 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001568
Facundo Batista353750c2007-09-13 18:13:15 +00001569 # if self is zero then exponent should be between Etiny and
1570 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1571 Etiny = context.Etiny()
1572 Etop = context.Etop()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001573 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00001574 exp_max = [context.Emax, Etop][context._clamp]
1575 new_exp = min(max(self._exp, Etiny), exp_max)
1576 if new_exp != self._exp:
1577 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001578 return _dec_from_triple(self._sign, '0', new_exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001579 else:
Facundo Batista6c398da2007-09-17 17:30:13 +00001580 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00001581
1582 # exp_min is the smallest allowable exponent of the result,
1583 # equal to max(self.adjusted()-context.prec+1, Etiny)
1584 exp_min = len(self._int) + self._exp - context.prec
1585 if exp_min > Etop:
1586 # overflow: exp_min > Etop iff self.adjusted() > Emax
1587 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001588 context._raise_error(Rounded)
Facundo Batista353750c2007-09-13 18:13:15 +00001589 return context._raise_error(Overflow, 'above Emax', self._sign)
1590 self_is_subnormal = exp_min < Etiny
1591 if self_is_subnormal:
1592 context._raise_error(Subnormal)
1593 exp_min = Etiny
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001594
Facundo Batista353750c2007-09-13 18:13:15 +00001595 # round if self has too many digits
1596 if self._exp < exp_min:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001597 context._raise_error(Rounded)
Facundo Batista2ec74152007-12-03 17:55:00 +00001598 digits = len(self._int) + self._exp - exp_min
1599 if digits < 0:
1600 self = _dec_from_triple(self._sign, '1', exp_min-1)
1601 digits = 0
1602 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1603 changed = this_function(digits)
1604 coeff = self._int[:digits] or '0'
1605 if changed == 1:
1606 coeff = str(int(coeff)+1)
1607 ans = _dec_from_triple(self._sign, coeff, exp_min)
1608
1609 if changed:
Facundo Batista353750c2007-09-13 18:13:15 +00001610 context._raise_error(Inexact)
1611 if self_is_subnormal:
1612 context._raise_error(Underflow)
1613 if not ans:
1614 # raise Clamped on underflow to 0
1615 context._raise_error(Clamped)
1616 elif len(ans._int) == context.prec+1:
1617 # we get here only if rescaling rounds the
1618 # cofficient up to exactly 10**context.prec
1619 if ans._exp < Etop:
Facundo Batista72bc54f2007-11-23 17:59:00 +00001620 ans = _dec_from_triple(ans._sign,
1621 ans._int[:-1], ans._exp+1)
Facundo Batista353750c2007-09-13 18:13:15 +00001622 else:
1623 # Inexact and Rounded have already been raised
1624 ans = context._raise_error(Overflow, 'above Emax',
1625 self._sign)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001626 return ans
1627
Facundo Batista353750c2007-09-13 18:13:15 +00001628 # fold down if _clamp == 1 and self has too few digits
1629 if context._clamp == 1 and self._exp > Etop:
1630 context._raise_error(Clamped)
Facundo Batista72bc54f2007-11-23 17:59:00 +00001631 self_padded = self._int + '0'*(self._exp - Etop)
1632 return _dec_from_triple(self._sign, self_padded, Etop)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001633
Facundo Batista353750c2007-09-13 18:13:15 +00001634 # here self was representable to begin with; return unchanged
Facundo Batista6c398da2007-09-17 17:30:13 +00001635 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001636
1637 _pick_rounding_function = {}
1638
Facundo Batista353750c2007-09-13 18:13:15 +00001639 # for each of the rounding functions below:
1640 # self is a finite, nonzero Decimal
1641 # prec is an integer satisfying 0 <= prec < len(self._int)
Facundo Batista2ec74152007-12-03 17:55:00 +00001642 #
1643 # each function returns either -1, 0, or 1, as follows:
1644 # 1 indicates that self should be rounded up (away from zero)
1645 # 0 indicates that self should be truncated, and that all the
1646 # digits to be truncated are zeros (so the value is unchanged)
1647 # -1 indicates that there are nonzero digits to be truncated
Facundo Batista353750c2007-09-13 18:13:15 +00001648
1649 def _round_down(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001650 """Also known as round-towards-0, truncate."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001651 if _all_zeros(self._int, prec):
1652 return 0
1653 else:
1654 return -1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001655
Facundo Batista353750c2007-09-13 18:13:15 +00001656 def _round_up(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001657 """Rounds away from 0."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001658 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001659
Facundo Batista353750c2007-09-13 18:13:15 +00001660 def _round_half_up(self, prec):
1661 """Rounds 5 up (away from 0)"""
Facundo Batista72bc54f2007-11-23 17:59:00 +00001662 if self._int[prec] in '56789':
Facundo Batista2ec74152007-12-03 17:55:00 +00001663 return 1
1664 elif _all_zeros(self._int, prec):
1665 return 0
Facundo Batista353750c2007-09-13 18:13:15 +00001666 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001667 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001668
1669 def _round_half_down(self, prec):
1670 """Round 5 down"""
Facundo Batista2ec74152007-12-03 17:55:00 +00001671 if _exact_half(self._int, prec):
1672 return -1
1673 else:
1674 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001675
1676 def _round_half_even(self, prec):
1677 """Round 5 to even, rest to nearest."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001678 if _exact_half(self._int, prec) and \
1679 (prec == 0 or self._int[prec-1] in '02468'):
1680 return -1
Facundo Batista353750c2007-09-13 18:13:15 +00001681 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001682 return self._round_half_up(prec)
Facundo Batista353750c2007-09-13 18:13:15 +00001683
1684 def _round_ceiling(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001685 """Rounds up (not away from 0 if negative.)"""
1686 if self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001687 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001688 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001689 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001690
Facundo Batista353750c2007-09-13 18:13:15 +00001691 def _round_floor(self, prec):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001692 """Rounds down (not towards 0 if negative)"""
1693 if not self._sign:
Facundo Batista353750c2007-09-13 18:13:15 +00001694 return self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001695 else:
Facundo Batista2ec74152007-12-03 17:55:00 +00001696 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001697
Facundo Batista353750c2007-09-13 18:13:15 +00001698 def _round_05up(self, prec):
1699 """Round down unless digit prec-1 is 0 or 5."""
Facundo Batista2ec74152007-12-03 17:55:00 +00001700 if prec and self._int[prec-1] not in '05':
Facundo Batista353750c2007-09-13 18:13:15 +00001701 return self._round_down(prec)
Facundo Batista2ec74152007-12-03 17:55:00 +00001702 else:
1703 return -self._round_down(prec)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001704
Facundo Batista353750c2007-09-13 18:13:15 +00001705 def fma(self, other, third, context=None):
1706 """Fused multiply-add.
1707
1708 Returns self*other+third with no rounding of the intermediate
1709 product self*other.
1710
1711 self and other are multiplied together, with no rounding of
1712 the result. The third operand is then added to the result,
1713 and a single final rounding is performed.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001714 """
Facundo Batista353750c2007-09-13 18:13:15 +00001715
1716 other = _convert_other(other, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001717
1718 # compute product; raise InvalidOperation if either operand is
1719 # a signaling NaN or if the product is zero times infinity.
1720 if self._is_special or other._is_special:
1721 if context is None:
1722 context = getcontext()
1723 if self._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001724 return context._raise_error(InvalidOperation, 'sNaN', self)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001725 if other._exp == 'N':
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001726 return context._raise_error(InvalidOperation, 'sNaN', other)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001727 if self._exp == 'n':
1728 product = self
1729 elif other._exp == 'n':
1730 product = other
1731 elif self._exp == 'F':
1732 if not other:
1733 return context._raise_error(InvalidOperation,
1734 'INF * 0 in fma')
1735 product = Infsign[self._sign ^ other._sign]
1736 elif other._exp == 'F':
1737 if not self:
1738 return context._raise_error(InvalidOperation,
1739 '0 * INF in fma')
1740 product = Infsign[self._sign ^ other._sign]
1741 else:
1742 product = _dec_from_triple(self._sign ^ other._sign,
1743 str(int(self._int) * int(other._int)),
1744 self._exp + other._exp)
1745
Facundo Batista353750c2007-09-13 18:13:15 +00001746 third = _convert_other(third, raiseit=True)
Facundo Batista58f6f2e2007-12-04 16:31:53 +00001747 return product.__add__(third, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001748
Facundo Batista353750c2007-09-13 18:13:15 +00001749 def _power_modulo(self, other, modulo, context=None):
1750 """Three argument version of __pow__"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001751
Facundo Batista353750c2007-09-13 18:13:15 +00001752 # if can't convert other and modulo to Decimal, raise
1753 # TypeError; there's no point returning NotImplemented (no
1754 # equivalent of __rpow__ for three argument pow)
1755 other = _convert_other(other, raiseit=True)
1756 modulo = _convert_other(modulo, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001757
Facundo Batista353750c2007-09-13 18:13:15 +00001758 if context is None:
1759 context = getcontext()
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001760
Facundo Batista353750c2007-09-13 18:13:15 +00001761 # deal with NaNs: if there are any sNaNs then first one wins,
1762 # (i.e. behaviour for NaNs is identical to that of fma)
1763 self_is_nan = self._isnan()
1764 other_is_nan = other._isnan()
1765 modulo_is_nan = modulo._isnan()
1766 if self_is_nan or other_is_nan or modulo_is_nan:
1767 if self_is_nan == 2:
1768 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001769 self)
Facundo Batista353750c2007-09-13 18:13:15 +00001770 if other_is_nan == 2:
1771 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001772 other)
Facundo Batista353750c2007-09-13 18:13:15 +00001773 if modulo_is_nan == 2:
1774 return context._raise_error(InvalidOperation, 'sNaN',
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00001775 modulo)
Facundo Batista353750c2007-09-13 18:13:15 +00001776 if self_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001777 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00001778 if other_is_nan:
Facundo Batista6c398da2007-09-17 17:30:13 +00001779 return other._fix_nan(context)
1780 return modulo._fix_nan(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00001781
Facundo Batista353750c2007-09-13 18:13:15 +00001782 # check inputs: we apply same restrictions as Python's pow()
1783 if not (self._isinteger() and
1784 other._isinteger() and
1785 modulo._isinteger()):
1786 return context._raise_error(InvalidOperation,
1787 'pow() 3rd argument not allowed '
1788 'unless all arguments are integers')
1789 if other < 0:
1790 return context._raise_error(InvalidOperation,
1791 'pow() 2nd argument cannot be '
1792 'negative when 3rd argument specified')
1793 if not modulo:
1794 return context._raise_error(InvalidOperation,
1795 'pow() 3rd argument cannot be 0')
1796
1797 # additional restriction for decimal: the modulus must be less
1798 # than 10**prec in absolute value
1799 if modulo.adjusted() >= context.prec:
1800 return context._raise_error(InvalidOperation,
1801 'insufficient precision: pow() 3rd '
1802 'argument must not have more than '
1803 'precision digits')
1804
1805 # define 0**0 == NaN, for consistency with two-argument pow
1806 # (even though it hurts!)
1807 if not other and not self:
1808 return context._raise_error(InvalidOperation,
1809 'at least one of pow() 1st argument '
1810 'and 2nd argument must be nonzero ;'
1811 '0**0 is not defined')
1812
1813 # compute sign of result
1814 if other._iseven():
1815 sign = 0
1816 else:
1817 sign = self._sign
1818
1819 # convert modulo to a Python integer, and self and other to
1820 # Decimal integers (i.e. force their exponents to be >= 0)
1821 modulo = abs(int(modulo))
1822 base = _WorkRep(self.to_integral_value())
1823 exponent = _WorkRep(other.to_integral_value())
1824
1825 # compute result using integer pow()
1826 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1827 for i in xrange(exponent.exp):
1828 base = pow(base, 10, modulo)
1829 base = pow(base, exponent.int, modulo)
1830
Facundo Batista72bc54f2007-11-23 17:59:00 +00001831 return _dec_from_triple(sign, str(base), 0)
Facundo Batista353750c2007-09-13 18:13:15 +00001832
1833 def _power_exact(self, other, p):
1834 """Attempt to compute self**other exactly.
1835
1836 Given Decimals self and other and an integer p, attempt to
1837 compute an exact result for the power self**other, with p
1838 digits of precision. Return None if self**other is not
1839 exactly representable in p digits.
1840
1841 Assumes that elimination of special cases has already been
1842 performed: self and other must both be nonspecial; self must
1843 be positive and not numerically equal to 1; other must be
1844 nonzero. For efficiency, other._exp should not be too large,
1845 so that 10**abs(other._exp) is a feasible calculation."""
1846
1847 # In the comments below, we write x for the value of self and
1848 # y for the value of other. Write x = xc*10**xe and y =
1849 # yc*10**ye.
1850
1851 # The main purpose of this method is to identify the *failure*
1852 # of x**y to be exactly representable with as little effort as
1853 # possible. So we look for cheap and easy tests that
1854 # eliminate the possibility of x**y being exact. Only if all
1855 # these tests are passed do we go on to actually compute x**y.
1856
1857 # Here's the main idea. First normalize both x and y. We
1858 # express y as a rational m/n, with m and n relatively prime
1859 # and n>0. Then for x**y to be exactly representable (at
1860 # *any* precision), xc must be the nth power of a positive
1861 # integer and xe must be divisible by n. If m is negative
1862 # then additionally xc must be a power of either 2 or 5, hence
1863 # a power of 2**n or 5**n.
1864 #
1865 # There's a limit to how small |y| can be: if y=m/n as above
1866 # then:
1867 #
1868 # (1) if xc != 1 then for the result to be representable we
1869 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1870 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1871 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1872 # representable.
1873 #
1874 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1875 # |y| < 1/|xe| then the result is not representable.
1876 #
1877 # Note that since x is not equal to 1, at least one of (1) and
1878 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1879 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1880 #
1881 # There's also a limit to how large y can be, at least if it's
1882 # positive: the normalized result will have coefficient xc**y,
1883 # so if it's representable then xc**y < 10**p, and y <
1884 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1885 # not exactly representable.
1886
1887 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1888 # so |y| < 1/xe and the result is not representable.
1889 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1890 # < 1/nbits(xc).
1891
1892 x = _WorkRep(self)
1893 xc, xe = x.int, x.exp
1894 while xc % 10 == 0:
1895 xc //= 10
1896 xe += 1
1897
1898 y = _WorkRep(other)
1899 yc, ye = y.int, y.exp
1900 while yc % 10 == 0:
1901 yc //= 10
1902 ye += 1
1903
1904 # case where xc == 1: result is 10**(xe*y), with xe*y
1905 # required to be an integer
1906 if xc == 1:
1907 if ye >= 0:
1908 exponent = xe*yc*10**ye
1909 else:
1910 exponent, remainder = divmod(xe*yc, 10**-ye)
1911 if remainder:
1912 return None
1913 if y.sign == 1:
1914 exponent = -exponent
1915 # if other is a nonnegative integer, use ideal exponent
1916 if other._isinteger() and other._sign == 0:
1917 ideal_exponent = self._exp*int(other)
1918 zeros = min(exponent-ideal_exponent, p-1)
1919 else:
1920 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00001921 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00001922
1923 # case where y is negative: xc must be either a power
1924 # of 2 or a power of 5.
1925 if y.sign == 1:
1926 last_digit = xc % 10
1927 if last_digit in (2,4,6,8):
1928 # quick test for power of 2
1929 if xc & -xc != xc:
1930 return None
1931 # now xc is a power of 2; e is its exponent
1932 e = _nbits(xc)-1
1933 # find e*y and xe*y; both must be integers
1934 if ye >= 0:
1935 y_as_int = yc*10**ye
1936 e = e*y_as_int
1937 xe = xe*y_as_int
1938 else:
1939 ten_pow = 10**-ye
1940 e, remainder = divmod(e*yc, ten_pow)
1941 if remainder:
1942 return None
1943 xe, remainder = divmod(xe*yc, ten_pow)
1944 if remainder:
1945 return None
1946
1947 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1948 return None
1949 xc = 5**e
1950
1951 elif last_digit == 5:
1952 # e >= log_5(xc) if xc is a power of 5; we have
1953 # equality all the way up to xc=5**2658
1954 e = _nbits(xc)*28//65
1955 xc, remainder = divmod(5**e, xc)
1956 if remainder:
1957 return None
1958 while xc % 5 == 0:
1959 xc //= 5
1960 e -= 1
1961 if ye >= 0:
1962 y_as_integer = yc*10**ye
1963 e = e*y_as_integer
1964 xe = xe*y_as_integer
1965 else:
1966 ten_pow = 10**-ye
1967 e, remainder = divmod(e*yc, ten_pow)
1968 if remainder:
1969 return None
1970 xe, remainder = divmod(xe*yc, ten_pow)
1971 if remainder:
1972 return None
1973 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1974 return None
1975 xc = 2**e
1976 else:
1977 return None
1978
1979 if xc >= 10**p:
1980 return None
1981 xe = -e-xe
Facundo Batista72bc54f2007-11-23 17:59:00 +00001982 return _dec_from_triple(0, str(xc), xe)
Facundo Batista353750c2007-09-13 18:13:15 +00001983
1984 # now y is positive; find m and n such that y = m/n
1985 if ye >= 0:
1986 m, n = yc*10**ye, 1
1987 else:
1988 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1989 return None
1990 xc_bits = _nbits(xc)
1991 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1992 return None
1993 m, n = yc, 10**(-ye)
1994 while m % 2 == n % 2 == 0:
1995 m //= 2
1996 n //= 2
1997 while m % 5 == n % 5 == 0:
1998 m //= 5
1999 n //= 5
2000
2001 # compute nth root of xc*10**xe
2002 if n > 1:
2003 # if 1 < xc < 2**n then xc isn't an nth power
2004 if xc != 1 and xc_bits <= n:
2005 return None
2006
2007 xe, rem = divmod(xe, n)
2008 if rem != 0:
2009 return None
2010
2011 # compute nth root of xc using Newton's method
2012 a = 1L << -(-_nbits(xc)//n) # initial estimate
2013 while True:
2014 q, r = divmod(xc, a**(n-1))
2015 if a <= q:
2016 break
2017 else:
2018 a = (a*(n-1) + q)//n
2019 if not (a == q and r == 0):
2020 return None
2021 xc = a
2022
2023 # now xc*10**xe is the nth root of the original xc*10**xe
2024 # compute mth power of xc*10**xe
2025
2026 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2027 # 10**p and the result is not representable.
2028 if xc > 1 and m > p*100//_log10_lb(xc):
2029 return None
2030 xc = xc**m
2031 xe *= m
2032 if xc > 10**p:
2033 return None
2034
2035 # by this point the result *is* exactly representable
2036 # adjust the exponent to get as close as possible to the ideal
2037 # exponent, if necessary
2038 str_xc = str(xc)
2039 if other._isinteger() and other._sign == 0:
2040 ideal_exponent = self._exp*int(other)
2041 zeros = min(xe-ideal_exponent, p-len(str_xc))
2042 else:
2043 zeros = 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002044 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
Facundo Batista353750c2007-09-13 18:13:15 +00002045
2046 def __pow__(self, other, modulo=None, context=None):
2047 """Return self ** other [ % modulo].
2048
2049 With two arguments, compute self**other.
2050
2051 With three arguments, compute (self**other) % modulo. For the
2052 three argument form, the following restrictions on the
2053 arguments hold:
2054
2055 - all three arguments must be integral
2056 - other must be nonnegative
2057 - either self or other (or both) must be nonzero
2058 - modulo must be nonzero and must have at most p digits,
2059 where p is the context precision.
2060
2061 If any of these restrictions is violated the InvalidOperation
2062 flag is raised.
2063
2064 The result of pow(self, other, modulo) is identical to the
2065 result that would be obtained by computing (self**other) %
2066 modulo with unbounded precision, but is computed more
2067 efficiently. It is always exact.
2068 """
2069
2070 if modulo is not None:
2071 return self._power_modulo(other, modulo, context)
2072
2073 other = _convert_other(other)
2074 if other is NotImplemented:
2075 return other
2076
2077 if context is None:
2078 context = getcontext()
2079
2080 # either argument is a NaN => result is NaN
2081 ans = self._check_nans(other, context)
2082 if ans:
2083 return ans
2084
2085 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2086 if not other:
2087 if not self:
2088 return context._raise_error(InvalidOperation, '0 ** 0')
2089 else:
2090 return Dec_p1
2091
2092 # result has sign 1 iff self._sign is 1 and other is an odd integer
2093 result_sign = 0
2094 if self._sign == 1:
2095 if other._isinteger():
2096 if not other._iseven():
2097 result_sign = 1
2098 else:
2099 # -ve**noninteger = NaN
2100 # (-0)**noninteger = 0**noninteger
2101 if self:
2102 return context._raise_error(InvalidOperation,
2103 'x ** y with x negative and y not an integer')
2104 # negate self, without doing any unwanted rounding
Facundo Batista72bc54f2007-11-23 17:59:00 +00002105 self = self.copy_negate()
Facundo Batista353750c2007-09-13 18:13:15 +00002106
2107 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2108 if not self:
2109 if other._sign == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002110 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002111 else:
2112 return Infsign[result_sign]
2113
2114 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002115 if self._isinfinity():
Facundo Batista353750c2007-09-13 18:13:15 +00002116 if other._sign == 0:
2117 return Infsign[result_sign]
2118 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002119 return _dec_from_triple(result_sign, '0', 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002120
Facundo Batista353750c2007-09-13 18:13:15 +00002121 # 1**other = 1, but the choice of exponent and the flags
2122 # depend on the exponent of self, and on whether other is a
2123 # positive integer, a negative integer, or neither
2124 if self == Dec_p1:
2125 if other._isinteger():
2126 # exp = max(self._exp*max(int(other), 0),
2127 # 1-context.prec) but evaluating int(other) directly
2128 # is dangerous until we know other is small (other
2129 # could be 1e999999999)
2130 if other._sign == 1:
2131 multiplier = 0
2132 elif other > context.prec:
2133 multiplier = context.prec
2134 else:
2135 multiplier = int(other)
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002136
Facundo Batista353750c2007-09-13 18:13:15 +00002137 exp = self._exp * multiplier
2138 if exp < 1-context.prec:
2139 exp = 1-context.prec
2140 context._raise_error(Rounded)
2141 else:
2142 context._raise_error(Inexact)
2143 context._raise_error(Rounded)
2144 exp = 1-context.prec
2145
Facundo Batista72bc54f2007-11-23 17:59:00 +00002146 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002147
2148 # compute adjusted exponent of self
2149 self_adj = self.adjusted()
2150
2151 # self ** infinity is infinity if self > 1, 0 if self < 1
2152 # self ** -infinity is infinity if self < 1, 0 if self > 1
2153 if other._isinfinity():
2154 if (other._sign == 0) == (self_adj < 0):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002155 return _dec_from_triple(result_sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002156 else:
2157 return Infsign[result_sign]
2158
2159 # from here on, the result always goes through the call
2160 # to _fix at the end of this function.
2161 ans = None
2162
2163 # crude test to catch cases of extreme overflow/underflow. If
2164 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2165 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2166 # self**other >= 10**(Emax+1), so overflow occurs. The test
2167 # for underflow is similar.
2168 bound = self._log10_exp_bound() + other.adjusted()
2169 if (self_adj >= 0) == (other._sign == 0):
2170 # self > 1 and other +ve, or self < 1 and other -ve
2171 # possibility of overflow
2172 if bound >= len(str(context.Emax)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002173 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002174 else:
2175 # self > 1 and other -ve, or self < 1 and other +ve
2176 # possibility of underflow to 0
2177 Etiny = context.Etiny()
2178 if bound >= len(str(-Etiny)):
Facundo Batista72bc54f2007-11-23 17:59:00 +00002179 ans = _dec_from_triple(result_sign, '1', Etiny-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002180
2181 # try for an exact result with precision +1
2182 if ans is None:
2183 ans = self._power_exact(other, context.prec + 1)
2184 if ans is not None and result_sign == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002185 ans = _dec_from_triple(1, ans._int, ans._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002186
2187 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2188 if ans is None:
2189 p = context.prec
2190 x = _WorkRep(self)
2191 xc, xe = x.int, x.exp
2192 y = _WorkRep(other)
2193 yc, ye = y.int, y.exp
2194 if y.sign == 1:
2195 yc = -yc
2196
2197 # compute correctly rounded result: start with precision +3,
2198 # then increase precision until result is unambiguously roundable
2199 extra = 3
2200 while True:
2201 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2202 if coeff % (5*10**(len(str(coeff))-p-1)):
2203 break
2204 extra += 3
2205
Facundo Batista72bc54f2007-11-23 17:59:00 +00002206 ans = _dec_from_triple(result_sign, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002207
2208 # the specification says that for non-integer other we need to
2209 # raise Inexact, even when the result is actually exact. In
2210 # the same way, we need to raise Underflow here if the result
2211 # is subnormal. (The call to _fix will take care of raising
2212 # Rounded and Subnormal, as usual.)
2213 if not other._isinteger():
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002214 context._raise_error(Inexact)
Facundo Batista353750c2007-09-13 18:13:15 +00002215 # pad with zeros up to length context.prec+1 if necessary
2216 if len(ans._int) <= context.prec:
2217 expdiff = context.prec+1 - len(ans._int)
Facundo Batista72bc54f2007-11-23 17:59:00 +00002218 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2219 ans._exp-expdiff)
Facundo Batista353750c2007-09-13 18:13:15 +00002220 if ans.adjusted() < context.Emin:
2221 context._raise_error(Underflow)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002222
Facundo Batista353750c2007-09-13 18:13:15 +00002223 # unlike exp, ln and log10, the power function respects the
2224 # rounding mode; no need to use ROUND_HALF_EVEN here
2225 ans = ans._fix(context)
2226 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002227
2228 def __rpow__(self, other, context=None):
2229 """Swaps self/other and returns __pow__."""
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002230 other = _convert_other(other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00002231 if other is NotImplemented:
2232 return other
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002233 return other.__pow__(self, context=context)
2234
2235 def normalize(self, context=None):
2236 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002237
Facundo Batista353750c2007-09-13 18:13:15 +00002238 if context is None:
2239 context = getcontext()
2240
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002241 if self._is_special:
2242 ans = self._check_nans(context=context)
2243 if ans:
2244 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002245
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002246 dup = self._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002247 if dup._isinfinity():
2248 return dup
2249
2250 if not dup:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002251 return _dec_from_triple(dup._sign, '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00002252 exp_max = [context.Emax, context.Etop()][context._clamp]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002253 end = len(dup._int)
2254 exp = dup._exp
Facundo Batista72bc54f2007-11-23 17:59:00 +00002255 while dup._int[end-1] == '0' and exp < exp_max:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002256 exp += 1
2257 end -= 1
Facundo Batista72bc54f2007-11-23 17:59:00 +00002258 return _dec_from_triple(dup._sign, dup._int[:end], exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002259
Facundo Batistabd2fe832007-09-13 18:42:09 +00002260 def quantize(self, exp, rounding=None, context=None, watchexp=True):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002261 """Quantize self so its exponent is the same as that of exp.
2262
2263 Similar to self._rescale(exp._exp) but with error checking.
2264 """
Facundo Batistabd2fe832007-09-13 18:42:09 +00002265 exp = _convert_other(exp, raiseit=True)
2266
Facundo Batista353750c2007-09-13 18:13:15 +00002267 if context is None:
2268 context = getcontext()
2269 if rounding is None:
2270 rounding = context.rounding
2271
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002272 if self._is_special or exp._is_special:
2273 ans = self._check_nans(exp, context)
2274 if ans:
2275 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002276
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002277 if exp._isinfinity() or self._isinfinity():
2278 if exp._isinfinity() and self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00002279 return Decimal(self) # if both are inf, it is OK
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002280 return context._raise_error(InvalidOperation,
2281 'quantize with one INF')
Facundo Batista353750c2007-09-13 18:13:15 +00002282
Facundo Batistabd2fe832007-09-13 18:42:09 +00002283 # if we're not watching exponents, do a simple rescale
2284 if not watchexp:
2285 ans = self._rescale(exp._exp, rounding)
2286 # raise Inexact and Rounded where appropriate
2287 if ans._exp > self._exp:
2288 context._raise_error(Rounded)
2289 if ans != self:
2290 context._raise_error(Inexact)
2291 return ans
2292
Facundo Batista353750c2007-09-13 18:13:15 +00002293 # exp._exp should be between Etiny and Emax
2294 if not (context.Etiny() <= exp._exp <= context.Emax):
2295 return context._raise_error(InvalidOperation,
2296 'target exponent out of bounds in quantize')
2297
2298 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002299 ans = _dec_from_triple(self._sign, '0', exp._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002300 return ans._fix(context)
2301
2302 self_adjusted = self.adjusted()
2303 if self_adjusted > context.Emax:
2304 return context._raise_error(InvalidOperation,
2305 'exponent of quantize result too large for current context')
2306 if self_adjusted - exp._exp + 1 > context.prec:
2307 return context._raise_error(InvalidOperation,
2308 'quantize result has too many digits for current context')
2309
2310 ans = self._rescale(exp._exp, rounding)
2311 if ans.adjusted() > context.Emax:
2312 return context._raise_error(InvalidOperation,
2313 'exponent of quantize result too large for current context')
2314 if len(ans._int) > context.prec:
2315 return context._raise_error(InvalidOperation,
2316 'quantize result has too many digits for current context')
2317
2318 # raise appropriate flags
2319 if ans._exp > self._exp:
2320 context._raise_error(Rounded)
2321 if ans != self:
2322 context._raise_error(Inexact)
2323 if ans and ans.adjusted() < context.Emin:
2324 context._raise_error(Subnormal)
2325
2326 # call to fix takes care of any necessary folddown
2327 ans = ans._fix(context)
2328 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002329
2330 def same_quantum(self, other):
Facundo Batista1a191df2007-10-02 17:01:24 +00002331 """Return True if self and other have the same exponent; otherwise
2332 return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002333
Facundo Batista1a191df2007-10-02 17:01:24 +00002334 If either operand is a special value, the following rules are used:
2335 * return True if both operands are infinities
2336 * return True if both operands are NaNs
2337 * otherwise, return False.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002338 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002339 other = _convert_other(other, raiseit=True)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002340 if self._is_special or other._is_special:
Facundo Batista1a191df2007-10-02 17:01:24 +00002341 return (self.is_nan() and other.is_nan() or
2342 self.is_infinite() and other.is_infinite())
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002343 return self._exp == other._exp
2344
Facundo Batista353750c2007-09-13 18:13:15 +00002345 def _rescale(self, exp, rounding):
2346 """Rescale self so that the exponent is exp, either by padding with zeros
2347 or by truncating digits, using the given rounding mode.
2348
2349 Specials are returned without change. This operation is
2350 quiet: it raises no flags, and uses no information from the
2351 context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002352
2353 exp = exp to scale to (an integer)
Facundo Batista353750c2007-09-13 18:13:15 +00002354 rounding = rounding mode
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002355 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002356 if self._is_special:
Facundo Batista6c398da2007-09-17 17:30:13 +00002357 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002358 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002359 return _dec_from_triple(self._sign, '0', exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002360
Facundo Batista353750c2007-09-13 18:13:15 +00002361 if self._exp >= exp:
2362 # pad answer with zeros if necessary
Facundo Batista72bc54f2007-11-23 17:59:00 +00002363 return _dec_from_triple(self._sign,
2364 self._int + '0'*(self._exp - exp), exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002365
Facundo Batista353750c2007-09-13 18:13:15 +00002366 # too many digits; round and lose data. If self.adjusted() <
2367 # exp-1, replace self by 10**(exp-1) before rounding
2368 digits = len(self._int) + self._exp - exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002369 if digits < 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002370 self = _dec_from_triple(self._sign, '1', exp-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002371 digits = 0
2372 this_function = getattr(self, self._pick_rounding_function[rounding])
Facundo Batista2ec74152007-12-03 17:55:00 +00002373 changed = this_function(digits)
2374 coeff = self._int[:digits] or '0'
2375 if changed == 1:
2376 coeff = str(int(coeff)+1)
2377 return _dec_from_triple(self._sign, coeff, exp)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002378
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00002379 def _round(self, places, rounding):
2380 """Round a nonzero, nonspecial Decimal to a fixed number of
2381 significant figures, using the given rounding mode.
2382
2383 Infinities, NaNs and zeros are returned unaltered.
2384
2385 This operation is quiet: it raises no flags, and uses no
2386 information from the context.
2387
2388 """
2389 if places <= 0:
2390 raise ValueError("argument should be at least 1 in _round")
2391 if self._is_special or not self:
2392 return Decimal(self)
2393 ans = self._rescale(self.adjusted()+1-places, rounding)
2394 # it can happen that the rescale alters the adjusted exponent;
2395 # for example when rounding 99.97 to 3 significant figures.
2396 # When this happens we end up with an extra 0 at the end of
2397 # the number; a second rescale fixes this.
2398 if ans.adjusted() != self.adjusted():
2399 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2400 return ans
2401
Facundo Batista353750c2007-09-13 18:13:15 +00002402 def to_integral_exact(self, rounding=None, context=None):
2403 """Rounds to a nearby integer.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002404
Facundo Batista353750c2007-09-13 18:13:15 +00002405 If no rounding mode is specified, take the rounding mode from
2406 the context. This method raises the Rounded and Inexact flags
2407 when appropriate.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002408
Facundo Batista353750c2007-09-13 18:13:15 +00002409 See also: to_integral_value, which does exactly the same as
2410 this method except that it doesn't raise Inexact or Rounded.
2411 """
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002412 if self._is_special:
2413 ans = self._check_nans(context=context)
2414 if ans:
2415 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002416 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002417 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002418 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002419 if not self:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002420 return _dec_from_triple(self._sign, '0', 0)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002421 if context is None:
2422 context = getcontext()
Facundo Batista353750c2007-09-13 18:13:15 +00002423 if rounding is None:
2424 rounding = context.rounding
2425 context._raise_error(Rounded)
2426 ans = self._rescale(0, rounding)
2427 if ans != self:
2428 context._raise_error(Inexact)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002429 return ans
2430
Facundo Batista353750c2007-09-13 18:13:15 +00002431 def to_integral_value(self, rounding=None, context=None):
2432 """Rounds to the nearest integer, without raising inexact, rounded."""
2433 if context is None:
2434 context = getcontext()
2435 if rounding is None:
2436 rounding = context.rounding
2437 if self._is_special:
2438 ans = self._check_nans(context=context)
2439 if ans:
2440 return ans
Facundo Batista6c398da2007-09-17 17:30:13 +00002441 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002442 if self._exp >= 0:
Facundo Batista6c398da2007-09-17 17:30:13 +00002443 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00002444 else:
2445 return self._rescale(0, rounding)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002446
Facundo Batista353750c2007-09-13 18:13:15 +00002447 # the method name changed, but we provide also the old one, for compatibility
2448 to_integral = to_integral_value
2449
2450 def sqrt(self, context=None):
2451 """Return the square root of self."""
Mark Dickinson3b24ccb2008-03-25 14:33:23 +00002452 if context is None:
2453 context = getcontext()
2454
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002455 if self._is_special:
2456 ans = self._check_nans(context=context)
2457 if ans:
2458 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002459
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002460 if self._isinfinity() and self._sign == 0:
2461 return Decimal(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002462
2463 if not self:
Facundo Batista353750c2007-09-13 18:13:15 +00002464 # exponent = self._exp // 2. sqrt(-0) = -0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002465 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
Facundo Batista353750c2007-09-13 18:13:15 +00002466 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002467
2468 if self._sign == 1:
2469 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2470
Facundo Batista353750c2007-09-13 18:13:15 +00002471 # At this point self represents a positive number. Let p be
2472 # the desired precision and express self in the form c*100**e
2473 # with c a positive real number and e an integer, c and e
2474 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2475 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2476 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2477 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2478 # the closest integer to sqrt(c) with the even integer chosen
2479 # in the case of a tie.
2480 #
2481 # To ensure correct rounding in all cases, we use the
2482 # following trick: we compute the square root to an extra
2483 # place (precision p+1 instead of precision p), rounding down.
2484 # Then, if the result is inexact and its last digit is 0 or 5,
2485 # we increase the last digit to 1 or 6 respectively; if it's
2486 # exact we leave the last digit alone. Now the final round to
2487 # p places (or fewer in the case of underflow) will round
2488 # correctly and raise the appropriate flags.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002489
Facundo Batista353750c2007-09-13 18:13:15 +00002490 # use an extra digit of precision
2491 prec = context.prec+1
2492
2493 # write argument in the form c*100**e where e = self._exp//2
2494 # is the 'ideal' exponent, to be used if the square root is
2495 # exactly representable. l is the number of 'digits' of c in
2496 # base 100, so that 100**(l-1) <= c < 100**l.
2497 op = _WorkRep(self)
2498 e = op.exp >> 1
2499 if op.exp & 1:
2500 c = op.int * 10
2501 l = (len(self._int) >> 1) + 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002502 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002503 c = op.int
2504 l = len(self._int)+1 >> 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002505
Facundo Batista353750c2007-09-13 18:13:15 +00002506 # rescale so that c has exactly prec base 100 'digits'
2507 shift = prec-l
2508 if shift >= 0:
2509 c *= 100**shift
2510 exact = True
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002511 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002512 c, remainder = divmod(c, 100**-shift)
2513 exact = not remainder
2514 e -= shift
Martin v. Löwiscfe31282006-07-19 17:18:32 +00002515
Facundo Batista353750c2007-09-13 18:13:15 +00002516 # find n = floor(sqrt(c)) using Newton's method
2517 n = 10**prec
2518 while True:
2519 q = c//n
2520 if n <= q:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002521 break
Facundo Batista353750c2007-09-13 18:13:15 +00002522 else:
2523 n = n + q >> 1
2524 exact = exact and n*n == c
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002525
Facundo Batista353750c2007-09-13 18:13:15 +00002526 if exact:
2527 # result is exact; rescale to use ideal exponent e
2528 if shift >= 0:
2529 # assert n % 10**shift == 0
2530 n //= 10**shift
2531 else:
2532 n *= 10**-shift
2533 e += shift
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002534 else:
Facundo Batista353750c2007-09-13 18:13:15 +00002535 # result is not exact; fix last digit as described above
2536 if n % 5 == 0:
2537 n += 1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002538
Facundo Batista72bc54f2007-11-23 17:59:00 +00002539 ans = _dec_from_triple(0, str(n), e)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002540
Facundo Batista353750c2007-09-13 18:13:15 +00002541 # round, and fit to current context
2542 context = context._shallow_copy()
2543 rounding = context._set_rounding(ROUND_HALF_EVEN)
Raymond Hettingerdab988d2004-10-09 07:10:44 +00002544 ans = ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00002545 context.rounding = rounding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002546
Facundo Batista353750c2007-09-13 18:13:15 +00002547 return ans
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002548
2549 def max(self, other, context=None):
2550 """Returns the larger value.
2551
Facundo Batista353750c2007-09-13 18:13:15 +00002552 Like max(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002553 NaN (and signals if one is sNaN). Also rounds.
2554 """
Facundo Batista353750c2007-09-13 18:13:15 +00002555 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002556
Facundo Batista6c398da2007-09-17 17:30:13 +00002557 if context is None:
2558 context = getcontext()
2559
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002560 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002561 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002562 # number is always returned
2563 sn = self._isnan()
2564 on = other._isnan()
2565 if sn or on:
2566 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002567 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002568 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002569 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002570 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002571
Mark Dickinson2fc92632008-02-06 22:10:50 +00002572 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002573 if c == 0:
Facundo Batista59c58842007-04-10 12:58:45 +00002574 # If both operands are finite and equal in numerical value
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002575 # then an ordering is applied:
2576 #
Facundo Batista59c58842007-04-10 12:58:45 +00002577 # If the signs differ then max returns the operand with the
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002578 # positive sign and min returns the operand with the negative sign
2579 #
Facundo Batista59c58842007-04-10 12:58:45 +00002580 # If the signs are the same then the exponent is used to select
Facundo Batista353750c2007-09-13 18:13:15 +00002581 # the result. This is exactly the ordering used in compare_total.
2582 c = self.compare_total(other)
2583
2584 if c == -1:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002585 ans = other
Facundo Batista353750c2007-09-13 18:13:15 +00002586 else:
2587 ans = self
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002588
Facundo Batistae64acfa2007-12-17 14:18:42 +00002589 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002590
2591 def min(self, other, context=None):
2592 """Returns the smaller value.
2593
Facundo Batista59c58842007-04-10 12:58:45 +00002594 Like min(self, other) except if one is not a number, returns
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002595 NaN (and signals if one is sNaN). Also rounds.
2596 """
Facundo Batista353750c2007-09-13 18:13:15 +00002597 other = _convert_other(other, raiseit=True)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002598
Facundo Batista6c398da2007-09-17 17:30:13 +00002599 if context is None:
2600 context = getcontext()
2601
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002602 if self._is_special or other._is_special:
Facundo Batista59c58842007-04-10 12:58:45 +00002603 # If one operand is a quiet NaN and the other is number, then the
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002604 # number is always returned
2605 sn = self._isnan()
2606 on = other._isnan()
2607 if sn or on:
2608 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002609 return self._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002610 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00002611 return other._fix_nan(context)
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002612 return self._check_nans(other, context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002613
Mark Dickinson2fc92632008-02-06 22:10:50 +00002614 c = self._cmp(other)
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00002615 if c == 0:
Facundo Batista353750c2007-09-13 18:13:15 +00002616 c = self.compare_total(other)
2617
2618 if c == -1:
2619 ans = self
2620 else:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002621 ans = other
Raymond Hettinger636a6b12004-09-19 01:54:09 +00002622
Facundo Batistae64acfa2007-12-17 14:18:42 +00002623 return ans._fix(context)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002624
2625 def _isinteger(self):
2626 """Returns whether self is an integer"""
Facundo Batista353750c2007-09-13 18:13:15 +00002627 if self._is_special:
2628 return False
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002629 if self._exp >= 0:
2630 return True
2631 rest = self._int[self._exp:]
Facundo Batista72bc54f2007-11-23 17:59:00 +00002632 return rest == '0'*len(rest)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002633
2634 def _iseven(self):
Facundo Batista353750c2007-09-13 18:13:15 +00002635 """Returns True if self is even. Assumes self is an integer."""
2636 if not self or self._exp > 0:
2637 return True
Facundo Batista72bc54f2007-11-23 17:59:00 +00002638 return self._int[-1+self._exp] in '02468'
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002639
2640 def adjusted(self):
2641 """Return the adjusted exponent of self"""
2642 try:
2643 return self._exp + len(self._int) - 1
Facundo Batista59c58842007-04-10 12:58:45 +00002644 # If NaN or Infinity, self._exp is string
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00002645 except TypeError:
2646 return 0
2647
Facundo Batista353750c2007-09-13 18:13:15 +00002648 def canonical(self, context=None):
2649 """Returns the same Decimal object.
2650
2651 As we do not have different encodings for the same number, the
2652 received object already is in its canonical form.
2653 """
2654 return self
2655
2656 def compare_signal(self, other, context=None):
2657 """Compares self to the other operand numerically.
2658
2659 It's pretty much like compare(), but all NaNs signal, with signaling
2660 NaNs taking precedence over quiet NaNs.
2661 """
Mark Dickinson2fc92632008-02-06 22:10:50 +00002662 other = _convert_other(other, raiseit = True)
2663 ans = self._compare_check_nans(other, context)
2664 if ans:
2665 return ans
Facundo Batista353750c2007-09-13 18:13:15 +00002666 return self.compare(other, context=context)
2667
2668 def compare_total(self, other):
2669 """Compares self to other using the abstract representations.
2670
2671 This is not like the standard compare, which use their numerical
2672 value. Note that a total ordering is defined for all possible abstract
2673 representations.
2674 """
2675 # if one is negative and the other is positive, it's easy
2676 if self._sign and not other._sign:
2677 return Dec_n1
2678 if not self._sign and other._sign:
2679 return Dec_p1
2680 sign = self._sign
2681
2682 # let's handle both NaN types
2683 self_nan = self._isnan()
2684 other_nan = other._isnan()
2685 if self_nan or other_nan:
2686 if self_nan == other_nan:
2687 if self._int < other._int:
2688 if sign:
2689 return Dec_p1
2690 else:
2691 return Dec_n1
2692 if self._int > other._int:
2693 if sign:
2694 return Dec_n1
2695 else:
2696 return Dec_p1
2697 return Dec_0
2698
2699 if sign:
2700 if self_nan == 1:
2701 return Dec_n1
2702 if other_nan == 1:
2703 return Dec_p1
2704 if self_nan == 2:
2705 return Dec_n1
2706 if other_nan == 2:
2707 return Dec_p1
2708 else:
2709 if self_nan == 1:
2710 return Dec_p1
2711 if other_nan == 1:
2712 return Dec_n1
2713 if self_nan == 2:
2714 return Dec_p1
2715 if other_nan == 2:
2716 return Dec_n1
2717
2718 if self < other:
2719 return Dec_n1
2720 if self > other:
2721 return Dec_p1
2722
2723 if self._exp < other._exp:
2724 if sign:
2725 return Dec_p1
2726 else:
2727 return Dec_n1
2728 if self._exp > other._exp:
2729 if sign:
2730 return Dec_n1
2731 else:
2732 return Dec_p1
2733 return Dec_0
2734
2735
2736 def compare_total_mag(self, other):
2737 """Compares self to other using abstract repr., ignoring sign.
2738
2739 Like compare_total, but with operand's sign ignored and assumed to be 0.
2740 """
2741 s = self.copy_abs()
2742 o = other.copy_abs()
2743 return s.compare_total(o)
2744
2745 def copy_abs(self):
2746 """Returns a copy with the sign set to 0. """
Facundo Batista72bc54f2007-11-23 17:59:00 +00002747 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002748
2749 def copy_negate(self):
2750 """Returns a copy with the sign inverted."""
2751 if self._sign:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002752 return _dec_from_triple(0, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002753 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00002754 return _dec_from_triple(1, self._int, self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002755
2756 def copy_sign(self, other):
2757 """Returns self with the sign of other."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002758 return _dec_from_triple(other._sign, self._int,
2759 self._exp, self._is_special)
Facundo Batista353750c2007-09-13 18:13:15 +00002760
2761 def exp(self, context=None):
2762 """Returns e ** self."""
2763
2764 if context is None:
2765 context = getcontext()
2766
2767 # exp(NaN) = NaN
2768 ans = self._check_nans(context=context)
2769 if ans:
2770 return ans
2771
2772 # exp(-Infinity) = 0
2773 if self._isinfinity() == -1:
2774 return Dec_0
2775
2776 # exp(0) = 1
2777 if not self:
2778 return Dec_p1
2779
2780 # exp(Infinity) = Infinity
2781 if self._isinfinity() == 1:
2782 return Decimal(self)
2783
2784 # the result is now guaranteed to be inexact (the true
2785 # mathematical result is transcendental). There's no need to
2786 # raise Rounded and Inexact here---they'll always be raised as
2787 # a result of the call to _fix.
2788 p = context.prec
2789 adj = self.adjusted()
2790
2791 # we only need to do any computation for quite a small range
2792 # of adjusted exponents---for example, -29 <= adj <= 10 for
2793 # the default context. For smaller exponent the result is
2794 # indistinguishable from 1 at the given precision, while for
2795 # larger exponent the result either overflows or underflows.
2796 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2797 # overflow
Facundo Batista72bc54f2007-11-23 17:59:00 +00002798 ans = _dec_from_triple(0, '1', context.Emax+1)
Facundo Batista353750c2007-09-13 18:13:15 +00002799 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2800 # underflow to 0
Facundo Batista72bc54f2007-11-23 17:59:00 +00002801 ans = _dec_from_triple(0, '1', context.Etiny()-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002802 elif self._sign == 0 and adj < -p:
2803 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002804 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
Facundo Batista353750c2007-09-13 18:13:15 +00002805 elif self._sign == 1 and adj < -p-1:
2806 # p+1 digits; final round will raise correct flags
Facundo Batista72bc54f2007-11-23 17:59:00 +00002807 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
Facundo Batista353750c2007-09-13 18:13:15 +00002808 # general case
2809 else:
2810 op = _WorkRep(self)
2811 c, e = op.int, op.exp
2812 if op.sign == 1:
2813 c = -c
2814
2815 # compute correctly rounded result: increase precision by
2816 # 3 digits at a time until we get an unambiguously
2817 # roundable result
2818 extra = 3
2819 while True:
2820 coeff, exp = _dexp(c, e, p+extra)
2821 if coeff % (5*10**(len(str(coeff))-p-1)):
2822 break
2823 extra += 3
2824
Facundo Batista72bc54f2007-11-23 17:59:00 +00002825 ans = _dec_from_triple(0, str(coeff), exp)
Facundo Batista353750c2007-09-13 18:13:15 +00002826
2827 # at this stage, ans should round correctly with *any*
2828 # rounding mode, not just with ROUND_HALF_EVEN
2829 context = context._shallow_copy()
2830 rounding = context._set_rounding(ROUND_HALF_EVEN)
2831 ans = ans._fix(context)
2832 context.rounding = rounding
2833
2834 return ans
2835
2836 def is_canonical(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002837 """Return True if self is canonical; otherwise return False.
2838
2839 Currently, the encoding of a Decimal instance is always
2840 canonical, so this method returns True for any Decimal.
2841 """
2842 return True
Facundo Batista353750c2007-09-13 18:13:15 +00002843
2844 def is_finite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002845 """Return True if self is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00002846
Facundo Batista1a191df2007-10-02 17:01:24 +00002847 A Decimal instance is considered finite if it is neither
2848 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00002849 """
Facundo Batista1a191df2007-10-02 17:01:24 +00002850 return not self._is_special
Facundo Batista353750c2007-09-13 18:13:15 +00002851
2852 def is_infinite(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002853 """Return True if self is infinite; otherwise return False."""
2854 return self._exp == 'F'
Facundo Batista353750c2007-09-13 18:13:15 +00002855
2856 def is_nan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002857 """Return True if self is a qNaN or sNaN; otherwise return False."""
2858 return self._exp in ('n', 'N')
Facundo Batista353750c2007-09-13 18:13:15 +00002859
2860 def is_normal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002861 """Return True if self is a normal number; otherwise return False."""
2862 if self._is_special or not self:
2863 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002864 if context is None:
2865 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002866 return context.Emin <= self.adjusted() <= context.Emax
Facundo Batista353750c2007-09-13 18:13:15 +00002867
2868 def is_qnan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002869 """Return True if self is a quiet NaN; otherwise return False."""
2870 return self._exp == 'n'
Facundo Batista353750c2007-09-13 18:13:15 +00002871
2872 def is_signed(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002873 """Return True if self is negative; otherwise return False."""
2874 return self._sign == 1
Facundo Batista353750c2007-09-13 18:13:15 +00002875
2876 def is_snan(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002877 """Return True if self is a signaling NaN; otherwise return False."""
2878 return self._exp == 'N'
Facundo Batista353750c2007-09-13 18:13:15 +00002879
2880 def is_subnormal(self, context=None):
Facundo Batista1a191df2007-10-02 17:01:24 +00002881 """Return True if self is subnormal; otherwise return False."""
2882 if self._is_special or not self:
2883 return False
Facundo Batista353750c2007-09-13 18:13:15 +00002884 if context is None:
2885 context = getcontext()
Facundo Batista1a191df2007-10-02 17:01:24 +00002886 return self.adjusted() < context.Emin
Facundo Batista353750c2007-09-13 18:13:15 +00002887
2888 def is_zero(self):
Facundo Batista1a191df2007-10-02 17:01:24 +00002889 """Return True if self is a zero; otherwise return False."""
Facundo Batista72bc54f2007-11-23 17:59:00 +00002890 return not self._is_special and self._int == '0'
Facundo Batista353750c2007-09-13 18:13:15 +00002891
2892 def _ln_exp_bound(self):
2893 """Compute a lower bound for the adjusted exponent of self.ln().
2894 In other words, compute r such that self.ln() >= 10**r. Assumes
2895 that self is finite and positive and that self != 1.
2896 """
2897
2898 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2899 adj = self._exp + len(self._int) - 1
2900 if adj >= 1:
2901 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2902 return len(str(adj*23//10)) - 1
2903 if adj <= -2:
2904 # argument <= 0.1
2905 return len(str((-1-adj)*23//10)) - 1
2906 op = _WorkRep(self)
2907 c, e = op.int, op.exp
2908 if adj == 0:
2909 # 1 < self < 10
2910 num = str(c-10**-e)
2911 den = str(c)
2912 return len(num) - len(den) - (num < den)
2913 # adj == -1, 0.1 <= self < 1
2914 return e + len(str(10**-e - c)) - 1
2915
2916
2917 def ln(self, context=None):
2918 """Returns the natural (base e) logarithm of self."""
2919
2920 if context is None:
2921 context = getcontext()
2922
2923 # ln(NaN) = NaN
2924 ans = self._check_nans(context=context)
2925 if ans:
2926 return ans
2927
2928 # ln(0.0) == -Infinity
2929 if not self:
2930 return negInf
2931
2932 # ln(Infinity) = Infinity
2933 if self._isinfinity() == 1:
2934 return Inf
2935
2936 # ln(1.0) == 0.0
2937 if self == Dec_p1:
2938 return Dec_0
2939
2940 # ln(negative) raises InvalidOperation
2941 if self._sign == 1:
2942 return context._raise_error(InvalidOperation,
2943 'ln of a negative value')
2944
2945 # result is irrational, so necessarily inexact
2946 op = _WorkRep(self)
2947 c, e = op.int, op.exp
2948 p = context.prec
2949
2950 # correctly rounded result: repeatedly increase precision by 3
2951 # until we get an unambiguously roundable result
2952 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2953 while True:
2954 coeff = _dlog(c, e, places)
2955 # assert len(str(abs(coeff)))-p >= 1
2956 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2957 break
2958 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00002959 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00002960
2961 context = context._shallow_copy()
2962 rounding = context._set_rounding(ROUND_HALF_EVEN)
2963 ans = ans._fix(context)
2964 context.rounding = rounding
2965 return ans
2966
2967 def _log10_exp_bound(self):
2968 """Compute a lower bound for the adjusted exponent of self.log10().
2969 In other words, find r such that self.log10() >= 10**r.
2970 Assumes that self is finite and positive and that self != 1.
2971 """
2972
2973 # For x >= 10 or x < 0.1 we only need a bound on the integer
2974 # part of log10(self), and this comes directly from the
2975 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2976 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2977 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2978
2979 adj = self._exp + len(self._int) - 1
2980 if adj >= 1:
2981 # self >= 10
2982 return len(str(adj))-1
2983 if adj <= -2:
2984 # self < 0.1
2985 return len(str(-1-adj))-1
2986 op = _WorkRep(self)
2987 c, e = op.int, op.exp
2988 if adj == 0:
2989 # 1 < self < 10
2990 num = str(c-10**-e)
2991 den = str(231*c)
2992 return len(num) - len(den) - (num < den) + 2
2993 # adj == -1, 0.1 <= self < 1
2994 num = str(10**-e-c)
2995 return len(num) + e - (num < "231") - 1
2996
2997 def log10(self, context=None):
2998 """Returns the base 10 logarithm of self."""
2999
3000 if context is None:
3001 context = getcontext()
3002
3003 # log10(NaN) = NaN
3004 ans = self._check_nans(context=context)
3005 if ans:
3006 return ans
3007
3008 # log10(0.0) == -Infinity
3009 if not self:
3010 return negInf
3011
3012 # log10(Infinity) = Infinity
3013 if self._isinfinity() == 1:
3014 return Inf
3015
3016 # log10(negative or -Infinity) raises InvalidOperation
3017 if self._sign == 1:
3018 return context._raise_error(InvalidOperation,
3019 'log10 of a negative value')
3020
3021 # log10(10**n) = n
Facundo Batista72bc54f2007-11-23 17:59:00 +00003022 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
Facundo Batista353750c2007-09-13 18:13:15 +00003023 # answer may need rounding
3024 ans = Decimal(self._exp + len(self._int) - 1)
3025 else:
3026 # result is irrational, so necessarily inexact
3027 op = _WorkRep(self)
3028 c, e = op.int, op.exp
3029 p = context.prec
3030
3031 # correctly rounded result: repeatedly increase precision
3032 # until result is unambiguously roundable
3033 places = p-self._log10_exp_bound()+2
3034 while True:
3035 coeff = _dlog10(c, e, places)
3036 # assert len(str(abs(coeff)))-p >= 1
3037 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3038 break
3039 places += 3
Facundo Batista72bc54f2007-11-23 17:59:00 +00003040 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
Facundo Batista353750c2007-09-13 18:13:15 +00003041
3042 context = context._shallow_copy()
3043 rounding = context._set_rounding(ROUND_HALF_EVEN)
3044 ans = ans._fix(context)
3045 context.rounding = rounding
3046 return ans
3047
3048 def logb(self, context=None):
3049 """ Returns the exponent of the magnitude of self's MSD.
3050
3051 The result is the integer which is the exponent of the magnitude
3052 of the most significant digit of self (as though it were truncated
3053 to a single digit while maintaining the value of that digit and
3054 without limiting the resulting exponent).
3055 """
3056 # logb(NaN) = NaN
3057 ans = self._check_nans(context=context)
3058 if ans:
3059 return ans
3060
3061 if context is None:
3062 context = getcontext()
3063
3064 # logb(+/-Inf) = +Inf
3065 if self._isinfinity():
3066 return Inf
3067
3068 # logb(0) = -Inf, DivisionByZero
3069 if not self:
Facundo Batistacce8df22007-09-18 16:53:18 +00003070 return context._raise_error(DivisionByZero, 'logb(0)', 1)
Facundo Batista353750c2007-09-13 18:13:15 +00003071
3072 # otherwise, simply return the adjusted exponent of self, as a
3073 # Decimal. Note that no attempt is made to fit the result
3074 # into the current context.
3075 return Decimal(self.adjusted())
3076
3077 def _islogical(self):
3078 """Return True if self is a logical operand.
3079
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00003080 For being logical, it must be a finite number with a sign of 0,
Facundo Batista353750c2007-09-13 18:13:15 +00003081 an exponent of 0, and a coefficient whose digits must all be
3082 either 0 or 1.
3083 """
3084 if self._sign != 0 or self._exp != 0:
3085 return False
3086 for dig in self._int:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003087 if dig not in '01':
Facundo Batista353750c2007-09-13 18:13:15 +00003088 return False
3089 return True
3090
3091 def _fill_logical(self, context, opa, opb):
3092 dif = context.prec - len(opa)
3093 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003094 opa = '0'*dif + opa
Facundo Batista353750c2007-09-13 18:13:15 +00003095 elif dif < 0:
3096 opa = opa[-context.prec:]
3097 dif = context.prec - len(opb)
3098 if dif > 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003099 opb = '0'*dif + opb
Facundo Batista353750c2007-09-13 18:13:15 +00003100 elif dif < 0:
3101 opb = opb[-context.prec:]
3102 return opa, opb
3103
3104 def logical_and(self, other, context=None):
3105 """Applies an 'and' operation between self and other's digits."""
3106 if context is None:
3107 context = getcontext()
3108 if not self._islogical() or not other._islogical():
3109 return context._raise_error(InvalidOperation)
3110
3111 # fill to context.prec
3112 (opa, opb) = self._fill_logical(context, self._int, other._int)
3113
3114 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003115 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3116 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003117
3118 def logical_invert(self, context=None):
3119 """Invert all its digits."""
3120 if context is None:
3121 context = getcontext()
Facundo Batista72bc54f2007-11-23 17:59:00 +00003122 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3123 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003124
3125 def logical_or(self, other, context=None):
3126 """Applies an 'or' operation between self and other's digits."""
3127 if context is None:
3128 context = getcontext()
3129 if not self._islogical() or not other._islogical():
3130 return context._raise_error(InvalidOperation)
3131
3132 # fill to context.prec
3133 (opa, opb) = self._fill_logical(context, self._int, other._int)
3134
3135 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003136 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3137 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003138
3139 def logical_xor(self, other, context=None):
3140 """Applies an 'xor' operation between self and other's digits."""
3141 if context is None:
3142 context = getcontext()
3143 if not self._islogical() or not other._islogical():
3144 return context._raise_error(InvalidOperation)
3145
3146 # fill to context.prec
3147 (opa, opb) = self._fill_logical(context, self._int, other._int)
3148
3149 # make the operation, and clean starting zeroes
Facundo Batista72bc54f2007-11-23 17:59:00 +00003150 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3151 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
Facundo Batista353750c2007-09-13 18:13:15 +00003152
3153 def max_mag(self, other, context=None):
3154 """Compares the values numerically with their sign ignored."""
3155 other = _convert_other(other, raiseit=True)
3156
Facundo Batista6c398da2007-09-17 17:30:13 +00003157 if context is None:
3158 context = getcontext()
3159
Facundo Batista353750c2007-09-13 18:13:15 +00003160 if self._is_special or other._is_special:
3161 # If one operand is a quiet NaN and the other is number, then the
3162 # number is always returned
3163 sn = self._isnan()
3164 on = other._isnan()
3165 if sn or on:
3166 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003167 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003168 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003169 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003170 return self._check_nans(other, context)
3171
Mark Dickinson2fc92632008-02-06 22:10:50 +00003172 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003173 if c == 0:
3174 c = self.compare_total(other)
3175
3176 if c == -1:
3177 ans = other
3178 else:
3179 ans = self
3180
Facundo Batistae64acfa2007-12-17 14:18:42 +00003181 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003182
3183 def min_mag(self, other, context=None):
3184 """Compares the values numerically with their sign ignored."""
3185 other = _convert_other(other, raiseit=True)
3186
Facundo Batista6c398da2007-09-17 17:30:13 +00003187 if context is None:
3188 context = getcontext()
3189
Facundo Batista353750c2007-09-13 18:13:15 +00003190 if self._is_special or other._is_special:
3191 # If one operand is a quiet NaN and the other is number, then the
3192 # number is always returned
3193 sn = self._isnan()
3194 on = other._isnan()
3195 if sn or on:
3196 if on == 1 and sn != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003197 return self._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003198 if sn == 1 and on != 2:
Facundo Batista6c398da2007-09-17 17:30:13 +00003199 return other._fix_nan(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003200 return self._check_nans(other, context)
3201
Mark Dickinson2fc92632008-02-06 22:10:50 +00003202 c = self.copy_abs()._cmp(other.copy_abs())
Facundo Batista353750c2007-09-13 18:13:15 +00003203 if c == 0:
3204 c = self.compare_total(other)
3205
3206 if c == -1:
3207 ans = self
3208 else:
3209 ans = other
3210
Facundo Batistae64acfa2007-12-17 14:18:42 +00003211 return ans._fix(context)
Facundo Batista353750c2007-09-13 18:13:15 +00003212
3213 def next_minus(self, context=None):
3214 """Returns the largest representable number smaller than itself."""
3215 if context is None:
3216 context = getcontext()
3217
3218 ans = self._check_nans(context=context)
3219 if ans:
3220 return ans
3221
3222 if self._isinfinity() == -1:
3223 return negInf
3224 if self._isinfinity() == 1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003225 return _dec_from_triple(0, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003226
3227 context = context.copy()
3228 context._set_rounding(ROUND_FLOOR)
3229 context._ignore_all_flags()
3230 new_self = self._fix(context)
3231 if new_self != self:
3232 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003233 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3234 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003235
3236 def next_plus(self, context=None):
3237 """Returns the smallest representable number larger than itself."""
3238 if context is None:
3239 context = getcontext()
3240
3241 ans = self._check_nans(context=context)
3242 if ans:
3243 return ans
3244
3245 if self._isinfinity() == 1:
3246 return Inf
3247 if self._isinfinity() == -1:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003248 return _dec_from_triple(1, '9'*context.prec, context.Etop())
Facundo Batista353750c2007-09-13 18:13:15 +00003249
3250 context = context.copy()
3251 context._set_rounding(ROUND_CEILING)
3252 context._ignore_all_flags()
3253 new_self = self._fix(context)
3254 if new_self != self:
3255 return new_self
Facundo Batista72bc54f2007-11-23 17:59:00 +00003256 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3257 context)
Facundo Batista353750c2007-09-13 18:13:15 +00003258
3259 def next_toward(self, other, context=None):
3260 """Returns the number closest to self, in the direction towards other.
3261
3262 The result is the closest representable number to self
3263 (excluding self) that is in the direction towards other,
3264 unless both have the same value. If the two operands are
3265 numerically equal, then the result is a copy of self with the
3266 sign set to be the same as the sign of other.
3267 """
3268 other = _convert_other(other, raiseit=True)
3269
3270 if context is None:
3271 context = getcontext()
3272
3273 ans = self._check_nans(other, context)
3274 if ans:
3275 return ans
3276
Mark Dickinson2fc92632008-02-06 22:10:50 +00003277 comparison = self._cmp(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003278 if comparison == 0:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003279 return self.copy_sign(other)
Facundo Batista353750c2007-09-13 18:13:15 +00003280
3281 if comparison == -1:
3282 ans = self.next_plus(context)
3283 else: # comparison == 1
3284 ans = self.next_minus(context)
3285
3286 # decide which flags to raise using value of ans
3287 if ans._isinfinity():
3288 context._raise_error(Overflow,
3289 'Infinite result from next_toward',
3290 ans._sign)
3291 context._raise_error(Rounded)
3292 context._raise_error(Inexact)
3293 elif ans.adjusted() < context.Emin:
3294 context._raise_error(Underflow)
3295 context._raise_error(Subnormal)
3296 context._raise_error(Rounded)
3297 context._raise_error(Inexact)
3298 # if precision == 1 then we don't raise Clamped for a
3299 # result 0E-Etiny.
3300 if not ans:
3301 context._raise_error(Clamped)
3302
3303 return ans
3304
3305 def number_class(self, context=None):
3306 """Returns an indication of the class of self.
3307
3308 The class is one of the following strings:
Facundo Batista0f5e7bf2007-12-19 12:53:01 +00003309 sNaN
3310 NaN
Facundo Batista353750c2007-09-13 18:13:15 +00003311 -Infinity
3312 -Normal
3313 -Subnormal
3314 -Zero
3315 +Zero
3316 +Subnormal
3317 +Normal
3318 +Infinity
3319 """
3320 if self.is_snan():
3321 return "sNaN"
3322 if self.is_qnan():
3323 return "NaN"
3324 inf = self._isinfinity()
3325 if inf == 1:
3326 return "+Infinity"
3327 if inf == -1:
3328 return "-Infinity"
3329 if self.is_zero():
3330 if self._sign:
3331 return "-Zero"
3332 else:
3333 return "+Zero"
3334 if context is None:
3335 context = getcontext()
3336 if self.is_subnormal(context=context):
3337 if self._sign:
3338 return "-Subnormal"
3339 else:
3340 return "+Subnormal"
3341 # just a normal, regular, boring number, :)
3342 if self._sign:
3343 return "-Normal"
3344 else:
3345 return "+Normal"
3346
3347 def radix(self):
3348 """Just returns 10, as this is Decimal, :)"""
3349 return Decimal(10)
3350
3351 def rotate(self, other, context=None):
3352 """Returns a rotated copy of self, value-of-other times."""
3353 if context is None:
3354 context = getcontext()
3355
3356 ans = self._check_nans(other, context)
3357 if ans:
3358 return ans
3359
3360 if other._exp != 0:
3361 return context._raise_error(InvalidOperation)
3362 if not (-context.prec <= int(other) <= context.prec):
3363 return context._raise_error(InvalidOperation)
3364
3365 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003366 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003367
3368 # get values, pad if necessary
3369 torot = int(other)
3370 rotdig = self._int
3371 topad = context.prec - len(rotdig)
3372 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003373 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003374
3375 # let's rotate!
3376 rotated = rotdig[torot:] + rotdig[:torot]
Facundo Batista72bc54f2007-11-23 17:59:00 +00003377 return _dec_from_triple(self._sign,
3378 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003379
3380 def scaleb (self, other, context=None):
3381 """Returns self operand after adding the second value to its exp."""
3382 if context is None:
3383 context = getcontext()
3384
3385 ans = self._check_nans(other, context)
3386 if ans:
3387 return ans
3388
3389 if other._exp != 0:
3390 return context._raise_error(InvalidOperation)
3391 liminf = -2 * (context.Emax + context.prec)
3392 limsup = 2 * (context.Emax + context.prec)
3393 if not (liminf <= int(other) <= limsup):
3394 return context._raise_error(InvalidOperation)
3395
3396 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003397 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003398
Facundo Batista72bc54f2007-11-23 17:59:00 +00003399 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
Facundo Batista353750c2007-09-13 18:13:15 +00003400 d = d._fix(context)
3401 return d
3402
3403 def shift(self, other, context=None):
3404 """Returns a shifted copy of self, value-of-other times."""
3405 if context is None:
3406 context = getcontext()
3407
3408 ans = self._check_nans(other, context)
3409 if ans:
3410 return ans
3411
3412 if other._exp != 0:
3413 return context._raise_error(InvalidOperation)
3414 if not (-context.prec <= int(other) <= context.prec):
3415 return context._raise_error(InvalidOperation)
3416
3417 if self._isinfinity():
Facundo Batista6c398da2007-09-17 17:30:13 +00003418 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003419
3420 # get values, pad if necessary
3421 torot = int(other)
3422 if not torot:
Facundo Batista6c398da2007-09-17 17:30:13 +00003423 return Decimal(self)
Facundo Batista353750c2007-09-13 18:13:15 +00003424 rotdig = self._int
3425 topad = context.prec - len(rotdig)
3426 if topad:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003427 rotdig = '0'*topad + rotdig
Facundo Batista353750c2007-09-13 18:13:15 +00003428
3429 # let's shift!
3430 if torot < 0:
3431 rotated = rotdig[:torot]
3432 else:
Facundo Batista72bc54f2007-11-23 17:59:00 +00003433 rotated = rotdig + '0'*torot
Facundo Batista353750c2007-09-13 18:13:15 +00003434 rotated = rotated[-context.prec:]
3435
Facundo Batista72bc54f2007-11-23 17:59:00 +00003436 return _dec_from_triple(self._sign,
3437 rotated.lstrip('0') or '0', self._exp)
Facundo Batista353750c2007-09-13 18:13:15 +00003438
Facundo Batista59c58842007-04-10 12:58:45 +00003439 # Support for pickling, copy, and deepcopy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003440 def __reduce__(self):
3441 return (self.__class__, (str(self),))
3442
3443 def __copy__(self):
3444 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003445 return self # I'm immutable; therefore I am my own clone
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003446 return self.__class__(str(self))
3447
3448 def __deepcopy__(self, memo):
3449 if type(self) == Decimal:
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003450 return self # My components are also immutable
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003451 return self.__class__(str(self))
3452
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003453 # PEP 3101 support. See also _parse_format_specifier and _format_align
3454 def __format__(self, specifier, context=None):
Mark Dickinsonf4da7772008-02-29 03:29:17 +00003455 """Format a Decimal instance according to the given specifier.
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00003456
3457 The specifier should be a standard format specifier, with the
3458 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3459 'F', 'g', 'G', and '%' are supported. If the formatting type
3460 is omitted it defaults to 'g' or 'G', depending on the value
3461 of context.capitals.
3462
3463 At this time the 'n' format specifier type (which is supposed
3464 to use the current locale) is not supported.
3465 """
3466
3467 # Note: PEP 3101 says that if the type is not present then
3468 # there should be at least one digit after the decimal point.
3469 # We take the liberty of ignoring this requirement for
3470 # Decimal---it's presumably there to make sure that
3471 # format(float, '') behaves similarly to str(float).
3472 if context is None:
3473 context = getcontext()
3474
3475 spec = _parse_format_specifier(specifier)
3476
3477 # special values don't care about the type or precision...
3478 if self._is_special:
3479 return _format_align(str(self), spec)
3480
3481 # a type of None defaults to 'g' or 'G', depending on context
3482 # if type is '%', adjust exponent of self accordingly
3483 if spec['type'] is None:
3484 spec['type'] = ['g', 'G'][context.capitals]
3485 elif spec['type'] == '%':
3486 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3487
3488 # round if necessary, taking rounding mode from the context
3489 rounding = context.rounding
3490 precision = spec['precision']
3491 if precision is not None:
3492 if spec['type'] in 'eE':
3493 self = self._round(precision+1, rounding)
3494 elif spec['type'] in 'gG':
3495 if len(self._int) > precision:
3496 self = self._round(precision, rounding)
3497 elif spec['type'] in 'fF%':
3498 self = self._rescale(-precision, rounding)
3499 # special case: zeros with a positive exponent can't be
3500 # represented in fixed point; rescale them to 0e0.
3501 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3502 self = self._rescale(0, rounding)
3503
3504 # figure out placement of the decimal point
3505 leftdigits = self._exp + len(self._int)
3506 if spec['type'] in 'fF%':
3507 dotplace = leftdigits
3508 elif spec['type'] in 'eE':
3509 if not self and precision is not None:
3510 dotplace = 1 - precision
3511 else:
3512 dotplace = 1
3513 elif spec['type'] in 'gG':
3514 if self._exp <= 0 and leftdigits > -6:
3515 dotplace = leftdigits
3516 else:
3517 dotplace = 1
3518
3519 # figure out main part of numeric string...
3520 if dotplace <= 0:
3521 num = '0.' + '0'*(-dotplace) + self._int
3522 elif dotplace >= len(self._int):
3523 # make sure we're not padding a '0' with extra zeros on the right
3524 assert dotplace==len(self._int) or self._int != '0'
3525 num = self._int + '0'*(dotplace-len(self._int))
3526 else:
3527 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3528
3529 # ...then the trailing exponent, or trailing '%'
3530 if leftdigits != dotplace or spec['type'] in 'eE':
3531 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3532 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3533 elif spec['type'] == '%':
3534 num = num + '%'
3535
3536 # add sign
3537 if self._sign == 1:
3538 num = '-' + num
3539 return _format_align(num, spec)
3540
3541
Facundo Batista72bc54f2007-11-23 17:59:00 +00003542def _dec_from_triple(sign, coefficient, exponent, special=False):
3543 """Create a decimal instance directly, without any validation,
3544 normalization (e.g. removal of leading zeros) or argument
3545 conversion.
3546
3547 This function is for *internal use only*.
3548 """
3549
3550 self = object.__new__(Decimal)
3551 self._sign = sign
3552 self._int = coefficient
3553 self._exp = exponent
3554 self._is_special = special
3555
3556 return self
3557
Facundo Batista59c58842007-04-10 12:58:45 +00003558##### Context class #######################################################
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003559
Martin v. Löwiscfe31282006-07-19 17:18:32 +00003560
3561# get rounding method function:
Facundo Batista59c58842007-04-10 12:58:45 +00003562rounding_functions = [name for name in Decimal.__dict__.keys()
3563 if name.startswith('_round_')]
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003564for name in rounding_functions:
Facundo Batista59c58842007-04-10 12:58:45 +00003565 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003566 globalname = name[1:].upper()
3567 val = globals()[globalname]
3568 Decimal._pick_rounding_function[val] = name
3569
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003570del name, val, globalname, rounding_functions
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003571
Nick Coghlanced12182006-09-02 03:54:17 +00003572class _ContextManager(object):
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003573 """Context manager class to support localcontext().
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003574
Nick Coghlanced12182006-09-02 03:54:17 +00003575 Sets a copy of the supplied context in __enter__() and restores
Nick Coghlan8b6999b2006-08-31 12:00:43 +00003576 the previous decimal context in __exit__()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003577 """
3578 def __init__(self, new_context):
Nick Coghlanced12182006-09-02 03:54:17 +00003579 self.new_context = new_context.copy()
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003580 def __enter__(self):
3581 self.saved_context = getcontext()
3582 setcontext(self.new_context)
3583 return self.new_context
3584 def __exit__(self, t, v, tb):
3585 setcontext(self.saved_context)
Guido van Rossum1a5e21e2006-02-28 21:57:43 +00003586
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003587class Context(object):
3588 """Contains the context for a Decimal instance.
3589
3590 Contains:
3591 prec - precision (for use in rounding, division, square roots..)
Facundo Batista59c58842007-04-10 12:58:45 +00003592 rounding - rounding type (how you round)
Raymond Hettingerbf440692004-07-10 14:14:37 +00003593 traps - If traps[exception] = 1, then the exception is
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003594 raised when it is caused. Otherwise, a value is
3595 substituted in.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003596 flags - When an exception is caused, flags[exception] is set.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003597 (Whether or not the trap_enabler is set)
3598 Should be reset by user of Decimal instance.
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003599 Emin - Minimum exponent
3600 Emax - Maximum exponent
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003601 capitals - If 1, 1*10^1 is printed as 1E+1.
3602 If 0, printed as 1e1
Raymond Hettingere0f15812004-07-05 05:36:39 +00003603 _clamp - If 1, change exponents if too high (Default 0)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003604 """
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003605
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003606 def __init__(self, prec=None, rounding=None,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003607 traps=None, flags=None,
Raymond Hettinger0ea241e2004-07-04 13:53:24 +00003608 Emin=None, Emax=None,
Raymond Hettingere0f15812004-07-05 05:36:39 +00003609 capitals=None, _clamp=0,
Raymond Hettingerabf8a562004-10-12 09:12:16 +00003610 _ignored_flags=None):
3611 if flags is None:
3612 flags = []
3613 if _ignored_flags is None:
3614 _ignored_flags = []
Raymond Hettingerbf440692004-07-10 14:14:37 +00003615 if not isinstance(flags, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003616 flags = dict([(s, int(s in flags)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003617 del s
Raymond Hettingerbf440692004-07-10 14:14:37 +00003618 if traps is not None and not isinstance(traps, dict):
Mark Dickinson71f3b852008-05-04 02:25:46 +00003619 traps = dict([(s, int(s in traps)) for s in _signals])
Raymond Hettingerb91af522004-07-14 16:35:30 +00003620 del s
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003621 for name, val in locals().items():
3622 if val is None:
Raymond Hettingereb260842005-06-07 18:52:34 +00003623 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003624 else:
3625 setattr(self, name, val)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003626 del self.self
3627
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003628 def __repr__(self):
Raymond Hettingerbf440692004-07-10 14:14:37 +00003629 """Show the current context."""
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003630 s = []
Facundo Batista59c58842007-04-10 12:58:45 +00003631 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3632 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3633 % vars(self))
3634 names = [f.__name__ for f, v in self.flags.items() if v]
3635 s.append('flags=[' + ', '.join(names) + ']')
3636 names = [t.__name__ for t, v in self.traps.items() if v]
3637 s.append('traps=[' + ', '.join(names) + ']')
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003638 return ', '.join(s) + ')'
3639
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003640 def clear_flags(self):
3641 """Reset all flags to zero"""
3642 for flag in self.flags:
Raymond Hettingerb1b605e2004-07-04 01:55:39 +00003643 self.flags[flag] = 0
Raymond Hettingerd9c0a7a2004-07-03 10:02:28 +00003644
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003645 def _shallow_copy(self):
3646 """Returns a shallow copy from self."""
Facundo Batistae64acfa2007-12-17 14:18:42 +00003647 nc = Context(self.prec, self.rounding, self.traps,
3648 self.flags, self.Emin, self.Emax,
3649 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003650 return nc
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003651
3652 def copy(self):
3653 """Returns a deep copy from self."""
Facundo Batista59c58842007-04-10 12:58:45 +00003654 nc = Context(self.prec, self.rounding, self.traps.copy(),
Facundo Batistae64acfa2007-12-17 14:18:42 +00003655 self.flags.copy(), self.Emin, self.Emax,
3656 self.capitals, self._clamp, self._ignored_flags)
Raymond Hettinger9fce44b2004-08-08 04:03:24 +00003657 return nc
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003658 __copy__ = copy
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003659
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003660 def _raise_error(self, condition, explanation = None, *args):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003661 """Handles an error
3662
3663 If the flag is in _ignored_flags, returns the default response.
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003664 Otherwise, it sets the flag, then, if the corresponding
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003665 trap_enabler is set, it reaises the exception. Otherwise, it returns
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003666 the default value after setting the flag.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003667 """
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003668 error = _condition_map.get(condition, condition)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003669 if error in self._ignored_flags:
Facundo Batista59c58842007-04-10 12:58:45 +00003670 # Don't touch the flag
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003671 return error().handle(self, *args)
3672
Mark Dickinson1840c1a2008-05-03 18:23:14 +00003673 self.flags[error] = 1
Raymond Hettingerbf440692004-07-10 14:14:37 +00003674 if not self.traps[error]:
Facundo Batista59c58842007-04-10 12:58:45 +00003675 # The errors define how to handle themselves.
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003676 return condition().handle(self, *args)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003677
3678 # Errors should only be risked on copies of the context
Facundo Batista59c58842007-04-10 12:58:45 +00003679 # self._ignored_flags = []
Mark Dickinson8aca9d02008-05-04 02:05:06 +00003680 raise error(explanation)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003681
3682 def _ignore_all_flags(self):
3683 """Ignore all flags, if they are raised"""
Raymond Hettingerfed52962004-07-14 15:41:57 +00003684 return self._ignore_flags(*_signals)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003685
3686 def _ignore_flags(self, *flags):
3687 """Ignore the flags, if they are raised"""
3688 # Do not mutate-- This way, copies of a context leave the original
3689 # alone.
3690 self._ignored_flags = (self._ignored_flags + list(flags))
3691 return list(flags)
3692
3693 def _regard_flags(self, *flags):
3694 """Stop ignoring the flags, if they are raised"""
3695 if flags and isinstance(flags[0], (tuple,list)):
3696 flags = flags[0]
3697 for flag in flags:
3698 self._ignored_flags.remove(flag)
3699
Nick Coghlan53663a62008-07-15 14:27:37 +00003700 # We inherit object.__hash__, so we must deny this explicitly
3701 __hash__ = None
Raymond Hettinger5aa478b2004-07-09 10:02:53 +00003702
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003703 def Etiny(self):
3704 """Returns Etiny (= Emin - prec + 1)"""
3705 return int(self.Emin - self.prec + 1)
3706
3707 def Etop(self):
Raymond Hettingere0f15812004-07-05 05:36:39 +00003708 """Returns maximum exponent (= Emax - prec + 1)"""
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003709 return int(self.Emax - self.prec + 1)
3710
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003711 def _set_rounding(self, type):
3712 """Sets the rounding type.
3713
3714 Sets the rounding type, and returns the current (previous)
3715 rounding type. Often used like:
3716
3717 context = context.copy()
3718 # so you don't change the calling context
3719 # if an error occurs in the middle.
3720 rounding = context._set_rounding(ROUND_UP)
3721 val = self.__sub__(other, context=context)
3722 context._set_rounding(rounding)
3723
3724 This will make it round up for that operation.
3725 """
3726 rounding = self.rounding
3727 self.rounding= type
3728 return rounding
3729
Raymond Hettingerfed52962004-07-14 15:41:57 +00003730 def create_decimal(self, num='0'):
Mark Dickinson59bc20b2008-01-12 01:56:00 +00003731 """Creates a new Decimal instance but using self as context.
3732
3733 This method implements the to-number operation of the
3734 IBM Decimal specification."""
3735
3736 if isinstance(num, basestring) and num != num.strip():
3737 return self._raise_error(ConversionSyntax,
3738 "no trailing or leading whitespace is "
3739 "permitted.")
3740
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003741 d = Decimal(num, context=self)
Facundo Batista353750c2007-09-13 18:13:15 +00003742 if d._isnan() and len(d._int) > self.prec - self._clamp:
3743 return self._raise_error(ConversionSyntax,
3744 "diagnostic info too long in NaN")
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003745 return d._fix(self)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003746
Facundo Batista59c58842007-04-10 12:58:45 +00003747 # Methods
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003748 def abs(self, a):
3749 """Returns the absolute value of the operand.
3750
3751 If the operand is negative, the result is the same as using the minus
Facundo Batista59c58842007-04-10 12:58:45 +00003752 operation on the operand. Otherwise, the result is the same as using
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003753 the plus operation on the operand.
3754
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003755 >>> ExtendedContext.abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003756 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003757 >>> ExtendedContext.abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003758 Decimal('100')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003759 >>> ExtendedContext.abs(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003760 Decimal('101.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003761 >>> ExtendedContext.abs(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003762 Decimal('101.5')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003763 """
3764 return a.__abs__(context=self)
3765
3766 def add(self, a, b):
3767 """Return the sum of the two operands.
3768
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003769 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003770 Decimal('19.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003771 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003772 Decimal('1.02E+4')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003773 """
3774 return a.__add__(b, context=self)
3775
3776 def _apply(self, a):
Raymond Hettingerdab988d2004-10-09 07:10:44 +00003777 return str(a._fix(self))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003778
Facundo Batista353750c2007-09-13 18:13:15 +00003779 def canonical(self, a):
3780 """Returns the same Decimal object.
3781
3782 As we do not have different encodings for the same number, the
3783 received object already is in its canonical form.
3784
3785 >>> ExtendedContext.canonical(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003786 Decimal('2.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003787 """
3788 return a.canonical(context=self)
3789
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003790 def compare(self, a, b):
3791 """Compares values numerically.
3792
3793 If the signs of the operands differ, a value representing each operand
3794 ('-1' if the operand is less than zero, '0' if the operand is zero or
3795 negative zero, or '1' if the operand is greater than zero) is used in
3796 place of that operand for the comparison instead of the actual
3797 operand.
3798
3799 The comparison is then effected by subtracting the second operand from
3800 the first and then returning a value according to the result of the
3801 subtraction: '-1' if the result is less than zero, '0' if the result is
3802 zero or negative zero, or '1' if the result is greater than zero.
3803
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003804 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003805 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003806 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003807 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003808 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003809 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003810 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003811 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003812 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003813 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003814 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003815 Decimal('-1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003816 """
3817 return a.compare(b, context=self)
3818
Facundo Batista353750c2007-09-13 18:13:15 +00003819 def compare_signal(self, a, b):
3820 """Compares the values of the two operands numerically.
3821
3822 It's pretty much like compare(), but all NaNs signal, with signaling
3823 NaNs taking precedence over quiet NaNs.
3824
3825 >>> c = ExtendedContext
3826 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003827 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003828 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003829 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003830 >>> c.flags[InvalidOperation] = 0
3831 >>> print c.flags[InvalidOperation]
3832 0
3833 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003834 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003835 >>> print c.flags[InvalidOperation]
3836 1
3837 >>> c.flags[InvalidOperation] = 0
3838 >>> print c.flags[InvalidOperation]
3839 0
3840 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003841 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00003842 >>> print c.flags[InvalidOperation]
3843 1
3844 """
3845 return a.compare_signal(b, context=self)
3846
3847 def compare_total(self, a, b):
3848 """Compares two operands using their abstract representation.
3849
3850 This is not like the standard compare, which use their numerical
3851 value. Note that a total ordering is defined for all possible abstract
3852 representations.
3853
3854 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003855 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003856 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003857 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003858 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003859 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003860 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003861 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003862 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003863 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003864 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003865 Decimal('-1')
Facundo Batista353750c2007-09-13 18:13:15 +00003866 """
3867 return a.compare_total(b)
3868
3869 def compare_total_mag(self, a, b):
3870 """Compares two operands using their abstract representation ignoring sign.
3871
3872 Like compare_total, but with operand's sign ignored and assumed to be 0.
3873 """
3874 return a.compare_total_mag(b)
3875
3876 def copy_abs(self, a):
3877 """Returns a copy of the operand with the sign set to 0.
3878
3879 >>> ExtendedContext.copy_abs(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003880 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003881 >>> ExtendedContext.copy_abs(Decimal('-100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003882 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00003883 """
3884 return a.copy_abs()
3885
3886 def copy_decimal(self, a):
3887 """Returns a copy of the decimal objet.
3888
3889 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003890 Decimal('2.1')
Facundo Batista353750c2007-09-13 18:13:15 +00003891 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003892 Decimal('-1.00')
Facundo Batista353750c2007-09-13 18:13:15 +00003893 """
Facundo Batista6c398da2007-09-17 17:30:13 +00003894 return Decimal(a)
Facundo Batista353750c2007-09-13 18:13:15 +00003895
3896 def copy_negate(self, a):
3897 """Returns a copy of the operand with the sign inverted.
3898
3899 >>> ExtendedContext.copy_negate(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003900 Decimal('-101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003901 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003902 Decimal('101.5')
Facundo Batista353750c2007-09-13 18:13:15 +00003903 """
3904 return a.copy_negate()
3905
3906 def copy_sign(self, a, b):
3907 """Copies the second operand's sign to the first one.
3908
3909 In detail, it returns a copy of the first operand with the sign
3910 equal to the sign of the second operand.
3911
3912 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003913 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003914 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003915 Decimal('1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003916 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003917 Decimal('-1.50')
Facundo Batista353750c2007-09-13 18:13:15 +00003918 >>> 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 """
3921 return a.copy_sign(b)
3922
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003923 def divide(self, a, b):
3924 """Decimal division in a specified context.
3925
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003926 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003927 Decimal('0.333333333')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003928 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003929 Decimal('0.666666667')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003930 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003931 Decimal('2.5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003932 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003933 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003934 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003935 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003936 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003937 Decimal('4.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003938 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003939 Decimal('1.20')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003940 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003941 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003942 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003943 Decimal('1000')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003944 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003945 Decimal('1.20E+6')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003946 """
3947 return a.__div__(b, context=self)
3948
3949 def divide_int(self, a, b):
3950 """Divides two numbers and returns the integer part of the result.
3951
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003952 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003953 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003954 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003955 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00003956 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003957 Decimal('3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00003958 """
3959 return a.__floordiv__(b, context=self)
3960
3961 def divmod(self, a, b):
3962 return a.__divmod__(b, context=self)
3963
Facundo Batista353750c2007-09-13 18:13:15 +00003964 def exp(self, a):
3965 """Returns e ** a.
3966
3967 >>> c = ExtendedContext.copy()
3968 >>> c.Emin = -999
3969 >>> c.Emax = 999
3970 >>> c.exp(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003971 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00003972 >>> c.exp(Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003973 Decimal('0.367879441')
Facundo Batista353750c2007-09-13 18:13:15 +00003974 >>> c.exp(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003975 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00003976 >>> c.exp(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003977 Decimal('2.71828183')
Facundo Batista353750c2007-09-13 18:13:15 +00003978 >>> c.exp(Decimal('0.693147181'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003979 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00003980 >>> c.exp(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003981 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00003982 """
3983 return a.exp(context=self)
3984
3985 def fma(self, a, b, c):
3986 """Returns a multiplied by b, plus c.
3987
3988 The first two operands are multiplied together, using multiply,
3989 the third operand is then added to the result of that
3990 multiplication, using add, all with only one final rounding.
3991
3992 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003993 Decimal('22')
Facundo Batista353750c2007-09-13 18:13:15 +00003994 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003995 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00003996 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00003997 Decimal('1.38435736E+12')
Facundo Batista353750c2007-09-13 18:13:15 +00003998 """
3999 return a.fma(b, c, context=self)
4000
4001 def is_canonical(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004002 """Return True if the operand is canonical; otherwise return False.
4003
4004 Currently, the encoding of a Decimal instance is always
4005 canonical, so this method returns True for any Decimal.
Facundo Batista353750c2007-09-13 18:13:15 +00004006
4007 >>> ExtendedContext.is_canonical(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004008 True
Facundo Batista353750c2007-09-13 18:13:15 +00004009 """
Facundo Batista1a191df2007-10-02 17:01:24 +00004010 return a.is_canonical()
Facundo Batista353750c2007-09-13 18:13:15 +00004011
4012 def is_finite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004013 """Return True if the operand is finite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004014
Facundo Batista1a191df2007-10-02 17:01:24 +00004015 A Decimal instance is considered finite if it is neither
4016 infinite nor a NaN.
Facundo Batista353750c2007-09-13 18:13:15 +00004017
4018 >>> ExtendedContext.is_finite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004019 True
Facundo Batista353750c2007-09-13 18:13:15 +00004020 >>> ExtendedContext.is_finite(Decimal('-0.3'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004021 True
Facundo Batista353750c2007-09-13 18:13:15 +00004022 >>> ExtendedContext.is_finite(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004023 True
Facundo Batista353750c2007-09-13 18:13:15 +00004024 >>> ExtendedContext.is_finite(Decimal('Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004025 False
Facundo Batista353750c2007-09-13 18:13:15 +00004026 >>> ExtendedContext.is_finite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004027 False
Facundo Batista353750c2007-09-13 18:13:15 +00004028 """
4029 return a.is_finite()
4030
4031 def is_infinite(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004032 """Return True if the operand is infinite; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004033
4034 >>> ExtendedContext.is_infinite(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004035 False
Facundo Batista353750c2007-09-13 18:13:15 +00004036 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004037 True
Facundo Batista353750c2007-09-13 18:13:15 +00004038 >>> ExtendedContext.is_infinite(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004039 False
Facundo Batista353750c2007-09-13 18:13:15 +00004040 """
4041 return a.is_infinite()
4042
4043 def is_nan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004044 """Return True if the operand is a qNaN or sNaN;
4045 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004046
4047 >>> ExtendedContext.is_nan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004048 False
Facundo Batista353750c2007-09-13 18:13:15 +00004049 >>> ExtendedContext.is_nan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004050 True
Facundo Batista353750c2007-09-13 18:13:15 +00004051 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004052 True
Facundo Batista353750c2007-09-13 18:13:15 +00004053 """
4054 return a.is_nan()
4055
4056 def is_normal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004057 """Return True if the operand is a normal number;
4058 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004059
4060 >>> c = ExtendedContext.copy()
4061 >>> c.Emin = -999
4062 >>> c.Emax = 999
4063 >>> c.is_normal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004064 True
Facundo Batista353750c2007-09-13 18:13:15 +00004065 >>> c.is_normal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004066 False
Facundo Batista353750c2007-09-13 18:13:15 +00004067 >>> c.is_normal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004068 False
Facundo Batista353750c2007-09-13 18:13:15 +00004069 >>> c.is_normal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004070 False
Facundo Batista353750c2007-09-13 18:13:15 +00004071 >>> c.is_normal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004072 False
Facundo Batista353750c2007-09-13 18:13:15 +00004073 """
4074 return a.is_normal(context=self)
4075
4076 def is_qnan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004077 """Return True if the operand is a quiet NaN; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004078
4079 >>> ExtendedContext.is_qnan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004080 False
Facundo Batista353750c2007-09-13 18:13:15 +00004081 >>> ExtendedContext.is_qnan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004082 True
Facundo Batista353750c2007-09-13 18:13:15 +00004083 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004084 False
Facundo Batista353750c2007-09-13 18:13:15 +00004085 """
4086 return a.is_qnan()
4087
4088 def is_signed(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004089 """Return True if the operand is negative; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004090
4091 >>> ExtendedContext.is_signed(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004092 False
Facundo Batista353750c2007-09-13 18:13:15 +00004093 >>> ExtendedContext.is_signed(Decimal('-12'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004094 True
Facundo Batista353750c2007-09-13 18:13:15 +00004095 >>> ExtendedContext.is_signed(Decimal('-0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004096 True
Facundo Batista353750c2007-09-13 18:13:15 +00004097 """
4098 return a.is_signed()
4099
4100 def is_snan(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004101 """Return True if the operand is a signaling NaN;
4102 otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004103
4104 >>> ExtendedContext.is_snan(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004105 False
Facundo Batista353750c2007-09-13 18:13:15 +00004106 >>> ExtendedContext.is_snan(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004107 False
Facundo Batista353750c2007-09-13 18:13:15 +00004108 >>> ExtendedContext.is_snan(Decimal('sNaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004109 True
Facundo Batista353750c2007-09-13 18:13:15 +00004110 """
4111 return a.is_snan()
4112
4113 def is_subnormal(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004114 """Return True if the operand is subnormal; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004115
4116 >>> c = ExtendedContext.copy()
4117 >>> c.Emin = -999
4118 >>> c.Emax = 999
4119 >>> c.is_subnormal(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004120 False
Facundo Batista353750c2007-09-13 18:13:15 +00004121 >>> c.is_subnormal(Decimal('0.1E-999'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004122 True
Facundo Batista353750c2007-09-13 18:13:15 +00004123 >>> c.is_subnormal(Decimal('0.00'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004124 False
Facundo Batista353750c2007-09-13 18:13:15 +00004125 >>> c.is_subnormal(Decimal('-Inf'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004126 False
Facundo Batista353750c2007-09-13 18:13:15 +00004127 >>> c.is_subnormal(Decimal('NaN'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004128 False
Facundo Batista353750c2007-09-13 18:13:15 +00004129 """
4130 return a.is_subnormal(context=self)
4131
4132 def is_zero(self, a):
Facundo Batista1a191df2007-10-02 17:01:24 +00004133 """Return True if the operand is a zero; otherwise return False.
Facundo Batista353750c2007-09-13 18:13:15 +00004134
4135 >>> ExtendedContext.is_zero(Decimal('0'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004136 True
Facundo Batista353750c2007-09-13 18:13:15 +00004137 >>> ExtendedContext.is_zero(Decimal('2.50'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004138 False
Facundo Batista353750c2007-09-13 18:13:15 +00004139 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
Facundo Batista1a191df2007-10-02 17:01:24 +00004140 True
Facundo Batista353750c2007-09-13 18:13:15 +00004141 """
4142 return a.is_zero()
4143
4144 def ln(self, a):
4145 """Returns the natural (base e) logarithm of the operand.
4146
4147 >>> c = ExtendedContext.copy()
4148 >>> c.Emin = -999
4149 >>> c.Emax = 999
4150 >>> c.ln(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004151 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004152 >>> c.ln(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004153 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004154 >>> c.ln(Decimal('2.71828183'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004155 Decimal('1.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004156 >>> c.ln(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004157 Decimal('2.30258509')
Facundo Batista353750c2007-09-13 18:13:15 +00004158 >>> c.ln(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004159 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004160 """
4161 return a.ln(context=self)
4162
4163 def log10(self, a):
4164 """Returns the base 10 logarithm of the operand.
4165
4166 >>> c = ExtendedContext.copy()
4167 >>> c.Emin = -999
4168 >>> c.Emax = 999
4169 >>> c.log10(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004170 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004171 >>> c.log10(Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004172 Decimal('-3')
Facundo Batista353750c2007-09-13 18:13:15 +00004173 >>> c.log10(Decimal('1.000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004174 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004175 >>> c.log10(Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004176 Decimal('0.301029996')
Facundo Batista353750c2007-09-13 18:13:15 +00004177 >>> c.log10(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004178 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004179 >>> c.log10(Decimal('70'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004180 Decimal('1.84509804')
Facundo Batista353750c2007-09-13 18:13:15 +00004181 >>> c.log10(Decimal('+Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004182 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004183 """
4184 return a.log10(context=self)
4185
4186 def logb(self, a):
4187 """ Returns the exponent of the magnitude of the operand's MSD.
4188
4189 The result is the integer which is the exponent of the magnitude
4190 of the most significant digit of the operand (as though the
4191 operand were truncated to a single digit while maintaining the
4192 value of that digit and without limiting the resulting exponent).
4193
4194 >>> ExtendedContext.logb(Decimal('250'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004195 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004196 >>> ExtendedContext.logb(Decimal('2.50'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004197 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004198 >>> ExtendedContext.logb(Decimal('0.03'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004199 Decimal('-2')
Facundo Batista353750c2007-09-13 18:13:15 +00004200 >>> ExtendedContext.logb(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004201 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004202 """
4203 return a.logb(context=self)
4204
4205 def logical_and(self, a, b):
4206 """Applies the logical operation 'and' between each operand's digits.
4207
4208 The operands must be both logical numbers.
4209
4210 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004211 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004212 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004213 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004214 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004215 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004216 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004217 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004218 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004219 Decimal('1000')
Facundo Batista353750c2007-09-13 18:13:15 +00004220 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004221 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004222 """
4223 return a.logical_and(b, context=self)
4224
4225 def logical_invert(self, a):
4226 """Invert all the digits in the operand.
4227
4228 The operand must be a logical number.
4229
4230 >>> ExtendedContext.logical_invert(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004231 Decimal('111111111')
Facundo Batista353750c2007-09-13 18:13:15 +00004232 >>> ExtendedContext.logical_invert(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004233 Decimal('111111110')
Facundo Batista353750c2007-09-13 18:13:15 +00004234 >>> ExtendedContext.logical_invert(Decimal('111111111'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004235 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004236 >>> ExtendedContext.logical_invert(Decimal('101010101'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004237 Decimal('10101010')
Facundo Batista353750c2007-09-13 18:13:15 +00004238 """
4239 return a.logical_invert(context=self)
4240
4241 def logical_or(self, a, b):
4242 """Applies the logical operation 'or' between each operand's digits.
4243
4244 The operands must be both logical numbers.
4245
4246 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004247 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004248 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004249 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004250 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004251 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004252 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004253 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004254 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004255 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004256 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004257 Decimal('1110')
Facundo Batista353750c2007-09-13 18:13:15 +00004258 """
4259 return a.logical_or(b, context=self)
4260
4261 def logical_xor(self, a, b):
4262 """Applies the logical operation 'xor' between each operand's digits.
4263
4264 The operands must be both logical numbers.
4265
4266 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004267 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004268 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004269 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004270 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004271 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004272 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004273 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004274 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004275 Decimal('110')
Facundo Batista353750c2007-09-13 18:13:15 +00004276 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004277 Decimal('1101')
Facundo Batista353750c2007-09-13 18:13:15 +00004278 """
4279 return a.logical_xor(b, context=self)
4280
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004281 def max(self, a,b):
4282 """max compares two values numerically and returns the maximum.
4283
4284 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004285 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004286 operation. If they are numerically equal then the left-hand operand
4287 is chosen as the result. Otherwise the maximum (closer to positive
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004288 infinity) of the two operands is chosen as the result.
4289
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004290 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004291 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004292 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004293 Decimal('3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004294 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004295 Decimal('1')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004296 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004297 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004298 """
4299 return a.max(b, context=self)
4300
Facundo Batista353750c2007-09-13 18:13:15 +00004301 def max_mag(self, a, b):
4302 """Compares the values numerically with their sign ignored."""
4303 return a.max_mag(b, context=self)
4304
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004305 def min(self, a,b):
4306 """min compares two values numerically and returns the minimum.
4307
4308 If either operand is a NaN then the general rules apply.
Andrew M. Kuchlingc8acc882008-01-16 00:32:03 +00004309 Otherwise, the operands are compared as though by the compare
Facundo Batista59c58842007-04-10 12:58:45 +00004310 operation. If they are numerically equal then the left-hand operand
4311 is chosen as the result. Otherwise the minimum (closer to negative
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004312 infinity) of the two operands is chosen as the result.
4313
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004314 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004315 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004316 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004317 Decimal('-10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004318 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004319 Decimal('1.0')
Raymond Hettingerd6c700a2004-08-17 06:39:37 +00004320 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004321 Decimal('7')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004322 """
4323 return a.min(b, context=self)
4324
Facundo Batista353750c2007-09-13 18:13:15 +00004325 def min_mag(self, a, b):
4326 """Compares the values numerically with their sign ignored."""
4327 return a.min_mag(b, context=self)
4328
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004329 def minus(self, a):
4330 """Minus corresponds to unary prefix minus in Python.
4331
4332 The operation is evaluated using the same rules as subtract; the
4333 operation minus(a) is calculated as subtract('0', a) where the '0'
4334 has the same exponent as the operand.
4335
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004336 >>> ExtendedContext.minus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004337 Decimal('-1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004338 >>> ExtendedContext.minus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004339 Decimal('1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004340 """
4341 return a.__neg__(context=self)
4342
4343 def multiply(self, a, b):
4344 """multiply multiplies two operands.
4345
Martin v. Löwiscfe31282006-07-19 17:18:32 +00004346 If either operand is a special value then the general rules apply.
4347 Otherwise, the operands are multiplied together ('long multiplication'),
4348 resulting in a number which may be as long as the sum of the lengths
4349 of the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004350
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004351 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004352 Decimal('3.60')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004353 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004354 Decimal('21')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004355 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004356 Decimal('0.72')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004357 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004358 Decimal('-0.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004359 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004360 Decimal('4.28135971E+11')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004361 """
4362 return a.__mul__(b, context=self)
4363
Facundo Batista353750c2007-09-13 18:13:15 +00004364 def next_minus(self, a):
4365 """Returns the largest representable number smaller than a.
4366
4367 >>> c = ExtendedContext.copy()
4368 >>> c.Emin = -999
4369 >>> c.Emax = 999
4370 >>> ExtendedContext.next_minus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004371 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004372 >>> c.next_minus(Decimal('1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004373 Decimal('0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004374 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004375 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004376 >>> c.next_minus(Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004377 Decimal('9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004378 """
4379 return a.next_minus(context=self)
4380
4381 def next_plus(self, a):
4382 """Returns the smallest representable number larger than a.
4383
4384 >>> c = ExtendedContext.copy()
4385 >>> c.Emin = -999
4386 >>> c.Emax = 999
4387 >>> ExtendedContext.next_plus(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004388 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004389 >>> c.next_plus(Decimal('-1E-1007'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004390 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004391 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004392 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004393 >>> c.next_plus(Decimal('-Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004394 Decimal('-9.99999999E+999')
Facundo Batista353750c2007-09-13 18:13:15 +00004395 """
4396 return a.next_plus(context=self)
4397
4398 def next_toward(self, a, b):
4399 """Returns the number closest to a, in direction towards b.
4400
4401 The result is the closest representable number from the first
4402 operand (but not the first operand) that is in the direction
4403 towards the second operand, unless the operands have the same
4404 value.
4405
4406 >>> c = ExtendedContext.copy()
4407 >>> c.Emin = -999
4408 >>> c.Emax = 999
4409 >>> c.next_toward(Decimal('1'), Decimal('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004410 Decimal('1.00000001')
Facundo Batista353750c2007-09-13 18:13:15 +00004411 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004412 Decimal('-0E-1007')
Facundo Batista353750c2007-09-13 18:13:15 +00004413 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004414 Decimal('-1.00000002')
Facundo Batista353750c2007-09-13 18:13:15 +00004415 >>> c.next_toward(Decimal('1'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004416 Decimal('0.999999999')
Facundo Batista353750c2007-09-13 18:13:15 +00004417 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
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('-10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004420 Decimal('-1.00000004')
Facundo Batista353750c2007-09-13 18:13:15 +00004421 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004422 Decimal('-0.00')
Facundo Batista353750c2007-09-13 18:13:15 +00004423 """
4424 return a.next_toward(b, context=self)
4425
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004426 def normalize(self, a):
Raymond Hettingere0f15812004-07-05 05:36:39 +00004427 """normalize reduces an operand to its simplest form.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004428
4429 Essentially a plus operation with all trailing zeros removed from the
4430 result.
4431
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004432 >>> ExtendedContext.normalize(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004433 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004434 >>> ExtendedContext.normalize(Decimal('-2.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004435 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004436 >>> ExtendedContext.normalize(Decimal('1.200'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004437 Decimal('1.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004438 >>> ExtendedContext.normalize(Decimal('-120'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004439 Decimal('-1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004440 >>> ExtendedContext.normalize(Decimal('120.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004441 Decimal('1.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004442 >>> ExtendedContext.normalize(Decimal('0.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004443 Decimal('0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004444 """
4445 return a.normalize(context=self)
4446
Facundo Batista353750c2007-09-13 18:13:15 +00004447 def number_class(self, a):
4448 """Returns an indication of the class of the operand.
4449
4450 The class is one of the following strings:
4451 -sNaN
4452 -NaN
4453 -Infinity
4454 -Normal
4455 -Subnormal
4456 -Zero
4457 +Zero
4458 +Subnormal
4459 +Normal
4460 +Infinity
4461
4462 >>> c = Context(ExtendedContext)
4463 >>> c.Emin = -999
4464 >>> c.Emax = 999
4465 >>> c.number_class(Decimal('Infinity'))
4466 '+Infinity'
4467 >>> c.number_class(Decimal('1E-10'))
4468 '+Normal'
4469 >>> c.number_class(Decimal('2.50'))
4470 '+Normal'
4471 >>> c.number_class(Decimal('0.1E-999'))
4472 '+Subnormal'
4473 >>> c.number_class(Decimal('0'))
4474 '+Zero'
4475 >>> c.number_class(Decimal('-0'))
4476 '-Zero'
4477 >>> c.number_class(Decimal('-0.1E-999'))
4478 '-Subnormal'
4479 >>> c.number_class(Decimal('-1E-10'))
4480 '-Normal'
4481 >>> c.number_class(Decimal('-2.50'))
4482 '-Normal'
4483 >>> c.number_class(Decimal('-Infinity'))
4484 '-Infinity'
4485 >>> c.number_class(Decimal('NaN'))
4486 'NaN'
4487 >>> c.number_class(Decimal('-NaN'))
4488 'NaN'
4489 >>> c.number_class(Decimal('sNaN'))
4490 'sNaN'
4491 """
4492 return a.number_class(context=self)
4493
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004494 def plus(self, a):
4495 """Plus corresponds to unary prefix plus in Python.
4496
4497 The operation is evaluated using the same rules as add; the
4498 operation plus(a) is calculated as add('0', a) where the '0'
4499 has the same exponent as the operand.
4500
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004501 >>> ExtendedContext.plus(Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004502 Decimal('1.3')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004503 >>> ExtendedContext.plus(Decimal('-1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004504 Decimal('-1.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004505 """
4506 return a.__pos__(context=self)
4507
4508 def power(self, a, b, modulo=None):
4509 """Raises a to the power of b, to modulo if given.
4510
Facundo Batista353750c2007-09-13 18:13:15 +00004511 With two arguments, compute a**b. If a is negative then b
4512 must be integral. The result will be inexact unless b is
4513 integral and the result is finite and can be expressed exactly
4514 in 'precision' digits.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004515
Facundo Batista353750c2007-09-13 18:13:15 +00004516 With three arguments, compute (a**b) % modulo. For the
4517 three argument form, the following restrictions on the
4518 arguments hold:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004519
Facundo Batista353750c2007-09-13 18:13:15 +00004520 - all three arguments must be integral
4521 - b must be nonnegative
4522 - at least one of a or b must be nonzero
4523 - modulo must be nonzero and have at most 'precision' digits
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004524
Facundo Batista353750c2007-09-13 18:13:15 +00004525 The result of pow(a, b, modulo) is identical to the result
4526 that would be obtained by computing (a**b) % modulo with
4527 unbounded precision, but is computed more efficiently. It is
4528 always exact.
4529
4530 >>> c = ExtendedContext.copy()
4531 >>> c.Emin = -999
4532 >>> c.Emax = 999
4533 >>> c.power(Decimal('2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004534 Decimal('8')
Facundo Batista353750c2007-09-13 18:13:15 +00004535 >>> c.power(Decimal('-2'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004536 Decimal('-8')
Facundo Batista353750c2007-09-13 18:13:15 +00004537 >>> c.power(Decimal('2'), Decimal('-3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004538 Decimal('0.125')
Facundo Batista353750c2007-09-13 18:13:15 +00004539 >>> c.power(Decimal('1.7'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004540 Decimal('69.7575744')
Facundo Batista353750c2007-09-13 18:13:15 +00004541 >>> c.power(Decimal('10'), Decimal('0.301029996'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004542 Decimal('2.00000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004543 >>> c.power(Decimal('Infinity'), Decimal('-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004544 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004545 >>> c.power(Decimal('Infinity'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004546 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004547 >>> c.power(Decimal('Infinity'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004548 Decimal('Infinity')
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('2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004556 Decimal('Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004557 >>> c.power(Decimal('0'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004558 Decimal('NaN')
Facundo Batista353750c2007-09-13 18:13:15 +00004559
4560 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004561 Decimal('11')
Facundo Batista353750c2007-09-13 18:13:15 +00004562 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004563 Decimal('-11')
Facundo Batista353750c2007-09-13 18:13:15 +00004564 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004565 Decimal('1')
Facundo Batista353750c2007-09-13 18:13:15 +00004566 >>> 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('23E12345'), Decimal('67E189'), Decimal('123456789'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004569 Decimal('11729830')
Facundo Batista353750c2007-09-13 18:13:15 +00004570 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004571 Decimal('-0')
Facundo Batista353750c2007-09-13 18:13:15 +00004572 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004573 Decimal('1')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004574 """
4575 return a.__pow__(b, modulo, context=self)
4576
4577 def quantize(self, a, b):
Facundo Batista59c58842007-04-10 12:58:45 +00004578 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004579
4580 The coefficient of the result is derived from that of the left-hand
Facundo Batista59c58842007-04-10 12:58:45 +00004581 operand. It may be rounded using the current rounding setting (if the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004582 exponent is being increased), multiplied by a positive power of ten (if
4583 the exponent is being decreased), or is unchanged (if the exponent is
4584 already equal to that of the right-hand operand).
4585
4586 Unlike other operations, if the length of the coefficient after the
4587 quantize operation would be greater than precision then an Invalid
Facundo Batista59c58842007-04-10 12:58:45 +00004588 operation condition is raised. This guarantees that, unless there is
4589 an error condition, the exponent of the result of a quantize is always
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004590 equal to that of the right-hand operand.
4591
4592 Also unlike other operations, quantize will never raise Underflow, even
4593 if the result is subnormal and inexact.
4594
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004595 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004596 Decimal('2.170')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004597 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004598 Decimal('2.17')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004599 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004600 Decimal('2.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004601 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004602 Decimal('2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004603 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004604 Decimal('0E+1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004605 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004606 Decimal('-Infinity')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004607 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004608 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004609 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004610 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004611 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004612 Decimal('-0E+5')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004613 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004614 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004615 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004616 Decimal('NaN')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004617 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004618 Decimal('217.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004619 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004620 Decimal('217')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004621 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004622 Decimal('2.2E+2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004623 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004624 Decimal('2E+2')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004625 """
4626 return a.quantize(b, context=self)
4627
Facundo Batista353750c2007-09-13 18:13:15 +00004628 def radix(self):
4629 """Just returns 10, as this is Decimal, :)
4630
4631 >>> ExtendedContext.radix()
Raymond Hettingerabe32372008-02-14 02:41:22 +00004632 Decimal('10')
Facundo Batista353750c2007-09-13 18:13:15 +00004633 """
4634 return Decimal(10)
4635
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004636 def remainder(self, a, b):
4637 """Returns the remainder from integer division.
4638
4639 The result is the residue of the dividend after the operation of
Facundo Batista59c58842007-04-10 12:58:45 +00004640 calculating integer division as described for divide-integer, rounded
Neal Norwitz0d4c06e2007-04-25 06:30:05 +00004641 to precision digits if necessary. The sign of the result, if
Facundo Batista59c58842007-04-10 12:58:45 +00004642 non-zero, is the same as that of the original dividend.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004643
4644 This operation will fail under the same conditions as integer division
4645 (that is, if integer division on the same two operands would fail, the
4646 remainder cannot be calculated).
4647
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004648 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004649 Decimal('2.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004650 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004651 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004652 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004653 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004654 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004655 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004656 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004657 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004658 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004659 Decimal('1.0')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004660 """
4661 return a.__mod__(b, context=self)
4662
4663 def remainder_near(self, a, b):
4664 """Returns to be "a - b * n", where n is the integer nearest the exact
4665 value of "x / b" (if two integers are equally near then the even one
Facundo Batista59c58842007-04-10 12:58:45 +00004666 is chosen). If the result is equal to 0 then its sign will be the
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004667 sign of a.
4668
4669 This operation will fail under the same conditions as integer division
4670 (that is, if integer division on the same two operands would fail, the
4671 remainder cannot be calculated).
4672
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004673 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004674 Decimal('-0.9')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004675 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004676 Decimal('-2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004677 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004678 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004679 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004680 Decimal('-1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004681 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004682 Decimal('0.2')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004683 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004684 Decimal('0.1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004685 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004686 Decimal('-0.3')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004687 """
4688 return a.remainder_near(b, context=self)
4689
Facundo Batista353750c2007-09-13 18:13:15 +00004690 def rotate(self, a, b):
4691 """Returns a rotated copy of a, b times.
4692
4693 The coefficient of the result is a rotated copy of the digits in
4694 the coefficient of the first operand. The number of places of
4695 rotation is taken from the absolute value of the second operand,
4696 with the rotation being to the left if the second operand is
4697 positive or to the right otherwise.
4698
4699 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004700 Decimal('400000003')
Facundo Batista353750c2007-09-13 18:13:15 +00004701 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004702 Decimal('12')
Facundo Batista353750c2007-09-13 18:13:15 +00004703 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004704 Decimal('891234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004705 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004706 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004707 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004708 Decimal('345678912')
Facundo Batista353750c2007-09-13 18:13:15 +00004709 """
4710 return a.rotate(b, context=self)
4711
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004712 def same_quantum(self, a, b):
4713 """Returns True if the two operands have the same exponent.
4714
4715 The result is never affected by either the sign or the coefficient of
4716 either operand.
4717
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004718 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004719 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004720 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004721 True
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004722 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004723 False
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004724 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004725 True
4726 """
4727 return a.same_quantum(b)
4728
Facundo Batista353750c2007-09-13 18:13:15 +00004729 def scaleb (self, a, b):
4730 """Returns the first operand after adding the second value its exp.
4731
4732 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004733 Decimal('0.0750')
Facundo Batista353750c2007-09-13 18:13:15 +00004734 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004735 Decimal('7.50')
Facundo Batista353750c2007-09-13 18:13:15 +00004736 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004737 Decimal('7.50E+3')
Facundo Batista353750c2007-09-13 18:13:15 +00004738 """
4739 return a.scaleb (b, context=self)
4740
4741 def shift(self, a, b):
4742 """Returns a shifted copy of a, b times.
4743
4744 The coefficient of the result is a shifted copy of the digits
4745 in the coefficient of the first operand. The number of places
4746 to shift is taken from the absolute value of the second operand,
4747 with the shift being to the left if the second operand is
4748 positive or to the right otherwise. Digits shifted into the
4749 coefficient are zeros.
4750
4751 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004752 Decimal('400000000')
Facundo Batista353750c2007-09-13 18:13:15 +00004753 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004754 Decimal('0')
Facundo Batista353750c2007-09-13 18:13:15 +00004755 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004756 Decimal('1234567')
Facundo Batista353750c2007-09-13 18:13:15 +00004757 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004758 Decimal('123456789')
Facundo Batista353750c2007-09-13 18:13:15 +00004759 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004760 Decimal('345678900')
Facundo Batista353750c2007-09-13 18:13:15 +00004761 """
4762 return a.shift(b, context=self)
4763
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004764 def sqrt(self, a):
Facundo Batista59c58842007-04-10 12:58:45 +00004765 """Square root of a non-negative number to context precision.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004766
4767 If the result must be inexact, it is rounded using the round-half-even
4768 algorithm.
4769
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004770 >>> ExtendedContext.sqrt(Decimal('0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004771 Decimal('0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004772 >>> ExtendedContext.sqrt(Decimal('-0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004773 Decimal('-0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004774 >>> ExtendedContext.sqrt(Decimal('0.39'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004775 Decimal('0.624499800')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004776 >>> ExtendedContext.sqrt(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004777 Decimal('10')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004778 >>> ExtendedContext.sqrt(Decimal('1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004779 Decimal('1')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004780 >>> ExtendedContext.sqrt(Decimal('1.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004781 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004782 >>> ExtendedContext.sqrt(Decimal('1.00'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004783 Decimal('1.0')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004784 >>> ExtendedContext.sqrt(Decimal('7'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004785 Decimal('2.64575131')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004786 >>> ExtendedContext.sqrt(Decimal('10'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004787 Decimal('3.16227766')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004788 >>> ExtendedContext.prec
Raymond Hettinger6ea48452004-07-03 12:26:21 +00004789 9
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004790 """
4791 return a.sqrt(context=self)
4792
4793 def subtract(self, a, b):
Georg Brandlf33d01d2005-08-22 19:35:18 +00004794 """Return the difference between the two operands.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004795
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004796 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004797 Decimal('0.23')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004798 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004799 Decimal('0.00')
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00004800 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004801 Decimal('-0.77')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004802 """
4803 return a.__sub__(b, context=self)
4804
4805 def to_eng_string(self, a):
4806 """Converts a number to a string, using scientific notation.
4807
4808 The operation is not affected by the context.
4809 """
4810 return a.to_eng_string(context=self)
4811
4812 def to_sci_string(self, a):
4813 """Converts a number to a string, using scientific notation.
4814
4815 The operation is not affected by the context.
4816 """
4817 return a.__str__(context=self)
4818
Facundo Batista353750c2007-09-13 18:13:15 +00004819 def to_integral_exact(self, a):
4820 """Rounds to an integer.
4821
4822 When the operand has a negative exponent, the result is the same
4823 as using the quantize() operation using the given operand as the
4824 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4825 of the operand as the precision setting; Inexact and Rounded flags
4826 are allowed in this operation. The rounding mode is taken from the
4827 context.
4828
4829 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004830 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004831 >>> ExtendedContext.to_integral_exact(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004832 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004833 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004834 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004835 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004836 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004837 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004838 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004839 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004840 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004841 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004842 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004843 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004844 Decimal('-Infinity')
Facundo Batista353750c2007-09-13 18:13:15 +00004845 """
4846 return a.to_integral_exact(context=self)
4847
4848 def to_integral_value(self, a):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004849 """Rounds to an integer.
4850
4851 When the operand has a negative exponent, the result is the same
4852 as using the quantize() operation using the given operand as the
4853 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4854 of the operand as the precision setting, except that no flags will
Facundo Batista59c58842007-04-10 12:58:45 +00004855 be set. The rounding mode is taken from the context.
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004856
Facundo Batista353750c2007-09-13 18:13:15 +00004857 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004858 Decimal('2')
Facundo Batista353750c2007-09-13 18:13:15 +00004859 >>> ExtendedContext.to_integral_value(Decimal('100'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004860 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004861 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004862 Decimal('100')
Facundo Batista353750c2007-09-13 18:13:15 +00004863 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004864 Decimal('102')
Facundo Batista353750c2007-09-13 18:13:15 +00004865 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004866 Decimal('-102')
Facundo Batista353750c2007-09-13 18:13:15 +00004867 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004868 Decimal('1.0E+6')
Facundo Batista353750c2007-09-13 18:13:15 +00004869 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004870 Decimal('7.89E+77')
Facundo Batista353750c2007-09-13 18:13:15 +00004871 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
Raymond Hettingerabe32372008-02-14 02:41:22 +00004872 Decimal('-Infinity')
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004873 """
Facundo Batista353750c2007-09-13 18:13:15 +00004874 return a.to_integral_value(context=self)
4875
4876 # the method name changed, but we provide also the old one, for compatibility
4877 to_integral = to_integral_value
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004878
4879class _WorkRep(object):
4880 __slots__ = ('sign','int','exp')
Raymond Hettinger17931de2004-10-27 06:21:46 +00004881 # sign: 0 or 1
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004882 # int: int or long
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004883 # exp: None, int, or string
4884
4885 def __init__(self, value=None):
4886 if value is None:
4887 self.sign = None
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004888 self.int = 0
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004889 self.exp = None
Raymond Hettinger17931de2004-10-27 06:21:46 +00004890 elif isinstance(value, Decimal):
4891 self.sign = value._sign
Facundo Batista72bc54f2007-11-23 17:59:00 +00004892 self.int = int(value._int)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004893 self.exp = value._exp
Raymond Hettinger17931de2004-10-27 06:21:46 +00004894 else:
4895 # assert isinstance(value, tuple)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004896 self.sign = value[0]
4897 self.int = value[1]
4898 self.exp = value[2]
4899
4900 def __repr__(self):
4901 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4902
4903 __str__ = __repr__
4904
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004905
4906
Facundo Batistae64acfa2007-12-17 14:18:42 +00004907def _normalize(op1, op2, prec = 0):
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004908 """Normalizes op1, op2 to have the same exp and length of coefficient.
4909
4910 Done during addition.
4911 """
Facundo Batista353750c2007-09-13 18:13:15 +00004912 if op1.exp < op2.exp:
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004913 tmp = op2
4914 other = op1
4915 else:
4916 tmp = op1
4917 other = op2
4918
Facundo Batista353750c2007-09-13 18:13:15 +00004919 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4920 # Then adding 10**exp to tmp has the same effect (after rounding)
4921 # as adding any positive quantity smaller than 10**exp; similarly
4922 # for subtraction. So if other is smaller than 10**exp we replace
4923 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
Facundo Batistae64acfa2007-12-17 14:18:42 +00004924 tmp_len = len(str(tmp.int))
4925 other_len = len(str(other.int))
4926 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4927 if other_len + other.exp - 1 < exp:
4928 other.int = 1
4929 other.exp = exp
Raymond Hettinger636a6b12004-09-19 01:54:09 +00004930
Facundo Batista353750c2007-09-13 18:13:15 +00004931 tmp.int *= 10 ** (tmp.exp - other.exp)
4932 tmp.exp = other.exp
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00004933 return op1, op2
4934
Facundo Batista353750c2007-09-13 18:13:15 +00004935##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4936
4937# This function from Tim Peters was taken from here:
4938# http://mail.python.org/pipermail/python-list/1999-July/007758.html
4939# The correction being in the function definition is for speed, and
4940# the whole function is not resolved with math.log because of avoiding
4941# the use of floats.
4942def _nbits(n, correction = {
4943 '0': 4, '1': 3, '2': 2, '3': 2,
4944 '4': 1, '5': 1, '6': 1, '7': 1,
4945 '8': 0, '9': 0, 'a': 0, 'b': 0,
4946 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4947 """Number of bits in binary representation of the positive integer n,
4948 or 0 if n == 0.
4949 """
4950 if n < 0:
4951 raise ValueError("The argument to _nbits should be nonnegative.")
4952 hex_n = "%x" % n
4953 return 4*len(hex_n) - correction[hex_n[0]]
4954
4955def _sqrt_nearest(n, a):
4956 """Closest integer to the square root of the positive integer n. a is
4957 an initial approximation to the square root. Any positive integer
4958 will do for a, but the closer a is to the square root of n the
4959 faster convergence will be.
4960
4961 """
4962 if n <= 0 or a <= 0:
4963 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4964
4965 b=0
4966 while a != b:
4967 b, a = a, a--n//a>>1
4968 return a
4969
4970def _rshift_nearest(x, shift):
4971 """Given an integer x and a nonnegative integer shift, return closest
4972 integer to x / 2**shift; use round-to-even in case of a tie.
4973
4974 """
4975 b, q = 1L << shift, x >> shift
4976 return q + (2*(x & (b-1)) + (q&1) > b)
4977
4978def _div_nearest(a, b):
4979 """Closest integer to a/b, a and b positive integers; rounds to even
4980 in the case of a tie.
4981
4982 """
4983 q, r = divmod(a, b)
4984 return q + (2*r + (q&1) > b)
4985
4986def _ilog(x, M, L = 8):
4987 """Integer approximation to M*log(x/M), with absolute error boundable
4988 in terms only of x/M.
4989
4990 Given positive integers x and M, return an integer approximation to
4991 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4992 between the approximation and the exact result is at most 22. For
4993 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4994 both cases these are upper bounds on the error; it will usually be
4995 much smaller."""
4996
4997 # The basic algorithm is the following: let log1p be the function
4998 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4999 # the reduction
5000 #
5001 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5002 #
5003 # repeatedly until the argument to log1p is small (< 2**-L in
5004 # absolute value). For small y we can use the Taylor series
5005 # expansion
5006 #
5007 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5008 #
5009 # truncating at T such that y**T is small enough. The whole
5010 # computation is carried out in a form of fixed-point arithmetic,
5011 # with a real number z being represented by an integer
5012 # approximation to z*M. To avoid loss of precision, the y below
5013 # is actually an integer approximation to 2**R*y*M, where R is the
5014 # number of reductions performed so far.
5015
5016 y = x-M
5017 # argument reduction; R = number of reductions performed
5018 R = 0
5019 while (R <= L and long(abs(y)) << L-R >= M or
5020 R > L and abs(y) >> R-L >= M):
5021 y = _div_nearest(long(M*y) << 1,
5022 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5023 R += 1
5024
5025 # Taylor series with T terms
5026 T = -int(-10*len(str(M))//(3*L))
5027 yshift = _rshift_nearest(y, R)
5028 w = _div_nearest(M, T)
5029 for k in xrange(T-1, 0, -1):
5030 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5031
5032 return _div_nearest(w*y, M)
5033
5034def _dlog10(c, e, p):
5035 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5036 approximation to 10**p * log10(c*10**e), with an absolute error of
5037 at most 1. Assumes that c*10**e is not exactly 1."""
5038
5039 # increase precision by 2; compensate for this by dividing
5040 # final result by 100
5041 p += 2
5042
5043 # write c*10**e as d*10**f with either:
5044 # f >= 0 and 1 <= d <= 10, or
5045 # f <= 0 and 0.1 <= d <= 1.
5046 # Thus for c*10**e close to 1, f = 0
5047 l = len(str(c))
5048 f = e+l - (e+l >= 1)
5049
5050 if p > 0:
5051 M = 10**p
5052 k = e+p-f
5053 if k >= 0:
5054 c *= 10**k
5055 else:
5056 c = _div_nearest(c, 10**-k)
5057
5058 log_d = _ilog(c, M) # error < 5 + 22 = 27
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005059 log_10 = _log10_digits(p) # error < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005060 log_d = _div_nearest(log_d*M, log_10)
5061 log_tenpower = f*M # exact
5062 else:
5063 log_d = 0 # error < 2.31
5064 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5065
5066 return _div_nearest(log_tenpower+log_d, 100)
5067
5068def _dlog(c, e, p):
5069 """Given integers c, e and p with c > 0, compute an integer
5070 approximation to 10**p * log(c*10**e), with an absolute error of
5071 at most 1. Assumes that c*10**e is not exactly 1."""
5072
5073 # Increase precision by 2. The precision increase is compensated
5074 # for at the end with a division by 100.
5075 p += 2
5076
5077 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5078 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5079 # as 10**p * log(d) + 10**p*f * log(10).
5080 l = len(str(c))
5081 f = e+l - (e+l >= 1)
5082
5083 # compute approximation to 10**p*log(d), with error < 27
5084 if p > 0:
5085 k = e+p-f
5086 if k >= 0:
5087 c *= 10**k
5088 else:
5089 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5090
5091 # _ilog magnifies existing error in c by a factor of at most 10
5092 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5093 else:
5094 # p <= 0: just approximate the whole thing by 0; error < 2.31
5095 log_d = 0
5096
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005097 # compute approximation to f*10**p*log(10), with error < 11.
Facundo Batista353750c2007-09-13 18:13:15 +00005098 if f:
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005099 extra = len(str(abs(f)))-1
5100 if p + extra >= 0:
5101 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5102 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5103 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
Facundo Batista353750c2007-09-13 18:13:15 +00005104 else:
5105 f_log_ten = 0
5106 else:
5107 f_log_ten = 0
5108
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005109 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
Facundo Batista353750c2007-09-13 18:13:15 +00005110 return _div_nearest(f_log_ten + log_d, 100)
5111
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005112class _Log10Memoize(object):
5113 """Class to compute, store, and allow retrieval of, digits of the
5114 constant log(10) = 2.302585.... This constant is needed by
5115 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5116 def __init__(self):
5117 self.digits = "23025850929940456840179914546843642076011014886"
5118
5119 def getdigits(self, p):
5120 """Given an integer p >= 0, return floor(10**p)*log(10).
5121
5122 For example, self.getdigits(3) returns 2302.
5123 """
5124 # digits are stored as a string, for quick conversion to
5125 # integer in the case that we've already computed enough
5126 # digits; the stored digits should always be correct
5127 # (truncated, not rounded to nearest).
5128 if p < 0:
5129 raise ValueError("p should be nonnegative")
5130
5131 if p >= len(self.digits):
5132 # compute p+3, p+6, p+9, ... digits; continue until at
5133 # least one of the extra digits is nonzero
5134 extra = 3
5135 while True:
5136 # compute p+extra digits, correct to within 1ulp
5137 M = 10**(p+extra+2)
5138 digits = str(_div_nearest(_ilog(10*M, M), 100))
5139 if digits[-extra:] != '0'*extra:
5140 break
5141 extra += 3
5142 # keep all reliable digits so far; remove trailing zeros
5143 # and next nonzero digit
5144 self.digits = digits.rstrip('0')[:-1]
5145 return int(self.digits[:p+1])
5146
5147_log10_digits = _Log10Memoize().getdigits
5148
Facundo Batista353750c2007-09-13 18:13:15 +00005149def _iexp(x, M, L=8):
5150 """Given integers x and M, M > 0, such that x/M is small in absolute
5151 value, compute an integer approximation to M*exp(x/M). For 0 <=
5152 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5153 is usually much smaller)."""
5154
5155 # Algorithm: to compute exp(z) for a real number z, first divide z
5156 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5157 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5158 # series
5159 #
5160 # expm1(x) = x + x**2/2! + x**3/3! + ...
5161 #
5162 # Now use the identity
5163 #
5164 # expm1(2x) = expm1(x)*(expm1(x)+2)
5165 #
5166 # R times to compute the sequence expm1(z/2**R),
5167 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5168
5169 # Find R such that x/2**R/M <= 2**-L
5170 R = _nbits((long(x)<<L)//M)
5171
5172 # Taylor series. (2**L)**T > M
5173 T = -int(-10*len(str(M))//(3*L))
5174 y = _div_nearest(x, T)
5175 Mshift = long(M)<<R
5176 for i in xrange(T-1, 0, -1):
5177 y = _div_nearest(x*(Mshift + y), Mshift * i)
5178
5179 # Expansion
5180 for k in xrange(R-1, -1, -1):
5181 Mshift = long(M)<<(k+2)
5182 y = _div_nearest(y*(y+Mshift), Mshift)
5183
5184 return M+y
5185
5186def _dexp(c, e, p):
5187 """Compute an approximation to exp(c*10**e), with p decimal places of
5188 precision.
5189
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005190 Returns integers d, f such that:
Facundo Batista353750c2007-09-13 18:13:15 +00005191
5192 10**(p-1) <= d <= 10**p, and
5193 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5194
5195 In other words, d*10**f is an approximation to exp(c*10**e) with p
5196 digits of precision, and with an error in d of at most 1. This is
5197 almost, but not quite, the same as the error being < 1ulp: when d
5198 = 10**(p-1) the error could be up to 10 ulp."""
5199
5200 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5201 p += 2
5202
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005203 # compute log(10) with extra precision = adjusted exponent of c*10**e
Facundo Batista353750c2007-09-13 18:13:15 +00005204 extra = max(0, e + len(str(c)) - 1)
5205 q = p + extra
Facundo Batista353750c2007-09-13 18:13:15 +00005206
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005207 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
Facundo Batista353750c2007-09-13 18:13:15 +00005208 # rounding down
5209 shift = e+q
5210 if shift >= 0:
5211 cshift = c*10**shift
5212 else:
5213 cshift = c//10**-shift
Facundo Batistabe6c7ba2007-10-02 18:21:18 +00005214 quot, rem = divmod(cshift, _log10_digits(q))
Facundo Batista353750c2007-09-13 18:13:15 +00005215
5216 # reduce remainder back to original precision
5217 rem = _div_nearest(rem, 10**extra)
5218
5219 # error in result of _iexp < 120; error after division < 0.62
5220 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5221
5222def _dpower(xc, xe, yc, ye, p):
5223 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5224 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5225
5226 10**(p-1) <= c <= 10**p, and
5227 (c-1)*10**e < x**y < (c+1)*10**e
5228
5229 in other words, c*10**e is an approximation to x**y with p digits
5230 of precision, and with an error in c of at most 1. (This is
5231 almost, but not quite, the same as the error being < 1ulp: when c
5232 == 10**(p-1) we can only guarantee error < 10ulp.)
5233
5234 We assume that: x is positive and not equal to 1, and y is nonzero.
5235 """
5236
5237 # Find b such that 10**(b-1) <= |y| <= 10**b
5238 b = len(str(abs(yc))) + ye
5239
5240 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5241 lxc = _dlog(xc, xe, p+b+1)
5242
5243 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5244 shift = ye-b
5245 if shift >= 0:
5246 pc = lxc*yc*10**shift
5247 else:
5248 pc = _div_nearest(lxc*yc, 10**-shift)
5249
5250 if pc == 0:
5251 # we prefer a result that isn't exactly 1; this makes it
5252 # easier to compute a correctly rounded result in __pow__
5253 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5254 coeff, exp = 10**(p-1)+1, 1-p
5255 else:
5256 coeff, exp = 10**p-1, -p
5257 else:
5258 coeff, exp = _dexp(pc, -(p+1), p+1)
5259 coeff = _div_nearest(coeff, 10)
5260 exp += 1
5261
5262 return coeff, exp
5263
5264def _log10_lb(c, correction = {
5265 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5266 '6': 23, '7': 16, '8': 10, '9': 5}):
5267 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5268 if c <= 0:
5269 raise ValueError("The argument to _log10_lb should be nonnegative.")
5270 str_c = str(c)
5271 return 100*len(str_c) - correction[str_c[0]]
5272
Facundo Batista59c58842007-04-10 12:58:45 +00005273##### Helper Functions ####################################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005274
Facundo Batista353750c2007-09-13 18:13:15 +00005275def _convert_other(other, raiseit=False):
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005276 """Convert other to Decimal.
5277
5278 Verifies that it's ok to use in an implicit construction.
5279 """
5280 if isinstance(other, Decimal):
5281 return other
5282 if isinstance(other, (int, long)):
5283 return Decimal(other)
Facundo Batista353750c2007-09-13 18:13:15 +00005284 if raiseit:
5285 raise TypeError("Unable to convert %s to Decimal" % other)
Raymond Hettinger267b8682005-03-27 10:47:39 +00005286 return NotImplemented
Raymond Hettinger636a6b12004-09-19 01:54:09 +00005287
Facundo Batista59c58842007-04-10 12:58:45 +00005288##### Setup Specific Contexts ############################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005289
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005290# The default context prototype used by Context()
Raymond Hettingerfed52962004-07-14 15:41:57 +00005291# Is mutable, so that new contexts can have different default values
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005292
5293DefaultContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005294 prec=28, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005295 traps=[DivisionByZero, Overflow, InvalidOperation],
5296 flags=[],
Raymond Hettinger99148e72004-07-14 19:56:56 +00005297 Emax=999999999,
5298 Emin=-999999999,
Raymond Hettingere0f15812004-07-05 05:36:39 +00005299 capitals=1
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005300)
5301
5302# Pre-made alternate contexts offered by the specification
5303# Don't change these; the user should be able to select these
5304# contexts and be able to reproduce results from other implementations
5305# of the spec.
5306
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005307BasicContext = Context(
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005308 prec=9, rounding=ROUND_HALF_UP,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005309 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5310 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005311)
5312
Raymond Hettinger9ec3e3b2004-07-03 13:48:56 +00005313ExtendedContext = Context(
Raymond Hettinger6ea48452004-07-03 12:26:21 +00005314 prec=9, rounding=ROUND_HALF_EVEN,
Raymond Hettingerbf440692004-07-10 14:14:37 +00005315 traps=[],
5316 flags=[],
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005317)
5318
5319
Facundo Batista72bc54f2007-11-23 17:59:00 +00005320##### crud for parsing strings #############################################
Mark Dickinson6a123cb2008-02-24 18:12:36 +00005321#
Facundo Batista72bc54f2007-11-23 17:59:00 +00005322# Regular expression used for parsing numeric strings. Additional
5323# comments:
5324#
5325# 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5326# whitespace. But note that the specification disallows whitespace in
5327# a numeric string.
5328#
5329# 2. For finite numbers (not infinities and NaNs) the body of the
5330# number between the optional sign and the optional exponent must have
5331# at least one decimal digit, possibly after the decimal point. The
5332# lookahead expression '(?=\d|\.\d)' checks this.
5333#
5334# As the flag UNICODE is not enabled here, we're explicitly avoiding any
5335# other meaning for \d than the numbers [0-9].
5336
5337import re
Mark Dickinson70c32892008-07-02 09:37:01 +00005338_parser = re.compile(r""" # A numeric string consists of:
Facundo Batista72bc54f2007-11-23 17:59:00 +00005339# \s*
Mark Dickinson70c32892008-07-02 09:37:01 +00005340 (?P<sign>[-+])? # an optional sign, followed by either...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005341 (
Mark Dickinson70c32892008-07-02 09:37:01 +00005342 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5343 (?P<int>[0-9]*) # having a (possibly empty) integer part
5344 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5345 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005346 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005347 Inf(inity)? # ...an infinity, or...
Facundo Batista72bc54f2007-11-23 17:59:00 +00005348 |
Mark Dickinson70c32892008-07-02 09:37:01 +00005349 (?P<signal>s)? # ...an (optionally signaling)
5350 NaN # NaN
5351 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
Facundo Batista72bc54f2007-11-23 17:59:00 +00005352 )
5353# \s*
Mark Dickinson59bc20b2008-01-12 01:56:00 +00005354 \Z
Facundo Batista72bc54f2007-11-23 17:59:00 +00005355""", re.VERBOSE | re.IGNORECASE).match
5356
Facundo Batista2ec74152007-12-03 17:55:00 +00005357_all_zeros = re.compile('0*$').match
5358_exact_half = re.compile('50*$').match
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005359
5360##### PEP3101 support functions ##############################################
5361# The functions parse_format_specifier and format_align have little to do
5362# with the Decimal class, and could potentially be reused for other pure
5363# Python numeric classes that want to implement __format__
5364#
5365# A format specifier for Decimal looks like:
5366#
5367# [[fill]align][sign][0][minimumwidth][.precision][type]
5368#
5369
5370_parse_format_specifier_regex = re.compile(r"""\A
5371(?:
5372 (?P<fill>.)?
5373 (?P<align>[<>=^])
5374)?
5375(?P<sign>[-+ ])?
5376(?P<zeropad>0)?
5377(?P<minimumwidth>(?!0)\d+)?
5378(?:\.(?P<precision>0|(?!0)\d+))?
5379(?P<type>[eEfFgG%])?
5380\Z
5381""", re.VERBOSE)
5382
Facundo Batista72bc54f2007-11-23 17:59:00 +00005383del re
5384
Mark Dickinson1ddf1d82008-02-29 02:16:37 +00005385def _parse_format_specifier(format_spec):
5386 """Parse and validate a format specifier.
5387
5388 Turns a standard numeric format specifier into a dict, with the
5389 following entries:
5390
5391 fill: fill character to pad field to minimum width
5392 align: alignment type, either '<', '>', '=' or '^'
5393 sign: either '+', '-' or ' '
5394 minimumwidth: nonnegative integer giving minimum width
5395 precision: nonnegative integer giving precision, or None
5396 type: one of the characters 'eEfFgG%', or None
5397 unicode: either True or False (always True for Python 3.x)
5398
5399 """
5400 m = _parse_format_specifier_regex.match(format_spec)
5401 if m is None:
5402 raise ValueError("Invalid format specifier: " + format_spec)
5403
5404 # get the dictionary
5405 format_dict = m.groupdict()
5406
5407 # defaults for fill and alignment
5408 fill = format_dict['fill']
5409 align = format_dict['align']
5410 if format_dict.pop('zeropad') is not None:
5411 # in the face of conflict, refuse the temptation to guess
5412 if fill is not None and fill != '0':
5413 raise ValueError("Fill character conflicts with '0'"
5414 " in format specifier: " + format_spec)
5415 if align is not None and align != '=':
5416 raise ValueError("Alignment conflicts with '0' in "
5417 "format specifier: " + format_spec)
5418 fill = '0'
5419 align = '='
5420 format_dict['fill'] = fill or ' '
5421 format_dict['align'] = align or '<'
5422
5423 if format_dict['sign'] is None:
5424 format_dict['sign'] = '-'
5425
5426 # turn minimumwidth and precision entries into integers.
5427 # minimumwidth defaults to 0; precision remains None if not given
5428 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5429 if format_dict['precision'] is not None:
5430 format_dict['precision'] = int(format_dict['precision'])
5431
5432 # if format type is 'g' or 'G' then a precision of 0 makes little
5433 # sense; convert it to 1. Same if format type is unspecified.
5434 if format_dict['precision'] == 0:
5435 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5436 format_dict['precision'] = 1
5437
5438 # record whether return type should be str or unicode
5439 format_dict['unicode'] = isinstance(format_spec, unicode)
5440
5441 return format_dict
5442
5443def _format_align(body, spec_dict):
5444 """Given an unpadded, non-aligned numeric string, add padding and
5445 aligment to conform with the given format specifier dictionary (as
5446 output from parse_format_specifier).
5447
5448 It's assumed that if body is negative then it starts with '-'.
5449 Any leading sign ('-' or '+') is stripped from the body before
5450 applying the alignment and padding rules, and replaced in the
5451 appropriate position.
5452
5453 """
5454 # figure out the sign; we only examine the first character, so if
5455 # body has leading whitespace the results may be surprising.
5456 if len(body) > 0 and body[0] in '-+':
5457 sign = body[0]
5458 body = body[1:]
5459 else:
5460 sign = ''
5461
5462 if sign != '-':
5463 if spec_dict['sign'] in ' +':
5464 sign = spec_dict['sign']
5465 else:
5466 sign = ''
5467
5468 # how much extra space do we have to play with?
5469 minimumwidth = spec_dict['minimumwidth']
5470 fill = spec_dict['fill']
5471 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5472
5473 align = spec_dict['align']
5474 if align == '<':
5475 result = padding + sign + body
5476 elif align == '>':
5477 result = sign + body + padding
5478 elif align == '=':
5479 result = sign + padding + body
5480 else: #align == '^'
5481 half = len(padding)//2
5482 result = padding[:half] + sign + body + padding[half:]
5483
5484 # make sure that result is unicode if necessary
5485 if spec_dict['unicode']:
5486 result = unicode(result)
5487
5488 return result
Facundo Batista72bc54f2007-11-23 17:59:00 +00005489
Facundo Batista59c58842007-04-10 12:58:45 +00005490##### Useful Constants (internal use only) ################################
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005491
Facundo Batista59c58842007-04-10 12:58:45 +00005492# Reusable defaults
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005493Inf = Decimal('Inf')
5494negInf = Decimal('-Inf')
Facundo Batista353750c2007-09-13 18:13:15 +00005495NaN = Decimal('NaN')
5496Dec_0 = Decimal(0)
5497Dec_p1 = Decimal(1)
5498Dec_n1 = Decimal(-1)
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005499
Facundo Batista59c58842007-04-10 12:58:45 +00005500# Infsign[sign] is infinity w/ that sign
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005501Infsign = (Inf, negInf)
5502
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005503
Raymond Hettinger7c85fa42004-07-01 11:01:35 +00005504
5505if __name__ == '__main__':
5506 import doctest, sys
5507 doctest.testmod(sys.modules[__name__])