Fixes (accepts patch) issue1339 - http://bugs.python.org/issue1339
[python.git] / Lib / decimal.py
blobe624a6dbbec16f4be98da63d00ae1240c2adf2c8
1 # Copyright (c) 2004 Python Software Foundation.
2 # All rights reserved.
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>
7 # and Aahz <aahz at pobox.com>
8 # and Tim Peters
10 # 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.
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.
20 """
21 This is a Py2.3 implementation of decimal floating point arithmetic based on
22 the General Decimal Arithmetic Specification:
24 www2.hursley.ibm.com/decimal/decarith.html
26 and IEEE standard 854-1987:
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
30 Decimal floating point has finite precision with arbitrarily large bounds.
32 The purpose of this module is to support arithmetic using familiar
33 "schoolhouse" rules and to avoid some of the tricky representation
34 issues associated with binary floating point. The package is especially
35 useful for financial applications or for contexts where users have
36 expectations that are at odds with binary floating point (for instance,
37 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38 of the expected Decimal("0.00") returned by decimal floating point).
40 Here are some examples of using the decimal module:
42 >>> from decimal import *
43 >>> setcontext(ExtendedContext)
44 >>> Decimal(0)
45 Decimal("0")
46 >>> Decimal("1")
47 Decimal("1")
48 >>> Decimal("-.0123")
49 Decimal("-0.0123")
50 >>> Decimal(123456)
51 Decimal("123456")
52 >>> Decimal("123.45e12345678901234567890")
53 Decimal("1.2345E+12345678901234567892")
54 >>> Decimal("1.33") + Decimal("1.27")
55 Decimal("2.60")
56 >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57 Decimal("-2.20")
58 >>> dig = Decimal(1)
59 >>> print dig / Decimal(3)
60 0.333333333
61 >>> getcontext().prec = 18
62 >>> print dig / Decimal(3)
63 0.333333333333333333
64 >>> print dig.sqrt()
66 >>> print Decimal(3).sqrt()
67 1.73205080756887729
68 >>> print Decimal(3) ** 123
69 4.85192780976896427E+58
70 >>> inf = Decimal(1) / Decimal(0)
71 >>> print inf
72 Infinity
73 >>> neginf = Decimal(-1) / Decimal(0)
74 >>> print neginf
75 -Infinity
76 >>> print neginf + inf
77 NaN
78 >>> print neginf * inf
79 -Infinity
80 >>> print dig / 0
81 Infinity
82 >>> getcontext().traps[DivisionByZero] = 1
83 >>> print dig / 0
84 Traceback (most recent call last):
85 ...
86 ...
87 ...
88 DivisionByZero: x / 0
89 >>> c = Context()
90 >>> c.traps[InvalidOperation] = 0
91 >>> print c.flags[InvalidOperation]
93 >>> c.divide(Decimal(0), Decimal(0))
94 Decimal("NaN")
95 >>> c.traps[InvalidOperation] = 1
96 >>> print c.flags[InvalidOperation]
98 >>> c.flags[InvalidOperation] = 0
99 >>> print c.flags[InvalidOperation]
101 >>> print c.divide(Decimal(0), Decimal(0))
102 Traceback (most recent call last):
106 InvalidOperation: 0 / 0
107 >>> print c.flags[InvalidOperation]
109 >>> c.flags[InvalidOperation] = 0
110 >>> c.traps[InvalidOperation] = 0
111 >>> print c.divide(Decimal(0), Decimal(0))
113 >>> print c.flags[InvalidOperation]
118 __all__ = [
119 # Two major classes
120 'Decimal', 'Context',
122 # Contexts
123 'DefaultContext', 'BasicContext', 'ExtendedContext',
125 # Exceptions
126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
133 # Functions for manipulating contexts
134 'setcontext', 'getcontext', 'localcontext'
137 import copy as _copy
139 try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142 except ImportError:
143 DecimalTuple = lambda *args: args
145 # Rounding
146 ROUND_DOWN = 'ROUND_DOWN'
147 ROUND_HALF_UP = 'ROUND_HALF_UP'
148 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149 ROUND_CEILING = 'ROUND_CEILING'
150 ROUND_FLOOR = 'ROUND_FLOOR'
151 ROUND_UP = 'ROUND_UP'
152 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
153 ROUND_05UP = 'ROUND_05UP'
155 # Errors
157 class DecimalException(ArithmeticError):
158 """Base exception class.
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.
166 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).)
173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
176 def handle(self, context, *args):
177 pass
180 class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
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
185 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
188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
192 class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
195 Various bad things cause this:
197 Something creates a signaling NaN
198 -INF + INF
199 0 * (+-)INF
200 (+-)INF / (+-)INF
201 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
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.
215 def handle(self, context, *args):
216 if args:
217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
219 return NaN
221 class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
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
226 syntax. The result is [0,qNaN].
228 def handle(self, context, *args):
229 return NaN
231 class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
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.
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.
244 def handle(self, context, sign, *args):
245 return Infsign[sign]
247 class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
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
252 longer than precision). The result is [0,qNaN].
255 def handle(self, context, *args):
256 return NaN
258 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
263 the dividend is also zero. The result is [0,qNaN].
266 def handle(self, context, *args):
267 return NaN
269 class Inexact(DecimalException):
270 """Had to round, losing information.
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
274 were non-zero), or if an overflow or underflow condition occurs. The
275 result in all cases is unchanged.
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
281 class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
284 This occurs and signals invalid-operation if an invalid context was
285 detected during an operation. This can occur if contexts are not checked
286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
288 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].
292 def handle(self, context, *args):
293 return NaN
295 class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
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
300 coefficient), or if an overflow or underflow condition occurs. The
301 result in all cases is unchanged.
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.
307 class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
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
312 Emin, before any rounding). The result in all cases is unchanged.
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.
318 class Overflow(Inexact, Rounded):
319 """Numerical overflow.
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).
326 The result depends on the rounding mode:
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],
330 where sign is the sign of the intermediate result. For round-down, the
331 result is the largest finite number that can be represented in the
332 current precision, with the sign of the intermediate result. For
333 round-ceiling, the result is the same as for round-down if the sign of
334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
335 the result is the same as for round-down if the sign of the intermediate
336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
337 will also be raised.
340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
342 ROUND_HALF_DOWN, ROUND_UP):
343 return Infsign[sign]
344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
346 return Infsign[sign]
347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
351 return Infsign[sign]
352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
356 class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
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
362 Emin). That is, the result is both inexact and subnormal.
364 The result after an underflow will be a subnormal number rounded, if
365 necessary, so that its exponent is not less than Etiny. This may result
366 in 0 with the sign of the intermediate result and an exponent of Etiny.
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 # List of public traps and flags
372 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
373 Underflow, InvalidOperation, Subnormal]
375 # Map conditions (per the spec) to signals
376 _condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
381 ##### Context Functions ##################################################
383 # 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
386 # work for older Pythons. If threads are not part of the build, create a
387 # mock threading object with threading.local() returning the module namespace.
389 try:
390 import threading
391 except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
394 class MockThreading(object):
395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
400 try:
401 threading.local
403 except AttributeError:
405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
407 if hasattr(threading.currentThread(), '__decimal_context__'):
408 del threading.currentThread().__decimal_context__
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
413 context = context.copy()
414 context.clear_flags()
415 threading.currentThread().__decimal_context__ = context
417 def getcontext():
418 """Returns this thread's context.
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.
424 try:
425 return threading.currentThread().__decimal_context__
426 except AttributeError:
427 context = Context()
428 threading.currentThread().__decimal_context__ = context
429 return context
431 else:
433 local = threading.local()
434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
437 def getcontext(_local=local):
438 """Returns this thread's context.
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.
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
454 context = context.copy()
455 context.clear_flags()
456 _local.__decimal_context__ = context
458 del threading, local # Don't contaminate the namespace
460 def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
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
471 return +s # Convert result to normal precision
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
478 return +s # Convert result to normal context
481 # The string below can't be included in the docstring until Python 2.6
482 # as the doctest module doesn't understand __future__ statements
484 >>> from __future__ import with_statement
485 >>> print getcontext().prec
487 >>> with localcontext():
488 ... ctx = getcontext()
489 ... ctx.prec += 2
490 ... print ctx.prec
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
497 >>> print getcontext().prec
500 if ctx is None: ctx = getcontext()
501 return _ContextManager(ctx)
504 ##### Decimal class #######################################################
506 class Decimal(object):
507 """Floating point class for decimal arithmetic."""
509 __slots__ = ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
514 # We're immutable, so use __new__ not __init__
515 def __new__(cls, value="0", context=None):
516 """Create a decimal point instance.
518 >>> Decimal('3.14') # string input
519 Decimal("3.14")
520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
521 Decimal("3.14")
522 >>> Decimal(314) # int or long
523 Decimal("314")
524 >>> Decimal(Decimal(314)) # another decimal instance
525 Decimal("314")
526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
527 Decimal("3.14")
530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
536 # digits.
538 self = object.__new__(cls)
540 # From a string
541 # REs insist on real strings, so we can too.
542 if isinstance(value, basestring):
543 m = _parser(value.strip())
544 if m is None:
545 if context is None:
546 context = getcontext()
547 return context._raise_error(ConversionSyntax,
548 "Invalid literal for Decimal: %r" % value)
550 if m.group('sign') == "-":
551 self._sign = 1
552 else:
553 self._sign = 0
554 intpart = m.group('int')
555 if intpart is not None:
556 # finite number
557 fracpart = m.group('frac')
558 exp = int(m.group('exp') or '0')
559 if fracpart is not None:
560 self._int = (intpart+fracpart).lstrip('0') or '0'
561 self._exp = exp - len(fracpart)
562 else:
563 self._int = intpart.lstrip('0') or '0'
564 self._exp = exp
565 self._is_special = False
566 else:
567 diag = m.group('diag')
568 if diag is not None:
569 # NaN
570 self._int = diag.lstrip('0')
571 if m.group('signal'):
572 self._exp = 'N'
573 else:
574 self._exp = 'n'
575 else:
576 # infinity
577 self._int = '0'
578 self._exp = 'F'
579 self._is_special = True
580 return self
582 # From an integer
583 if isinstance(value, (int,long)):
584 if value >= 0:
585 self._sign = 0
586 else:
587 self._sign = 1
588 self._exp = 0
589 self._int = str(abs(value))
590 self._is_special = False
591 return self
593 # From another decimal
594 if isinstance(value, Decimal):
595 self._exp = value._exp
596 self._sign = value._sign
597 self._int = value._int
598 self._is_special = value._is_special
599 return self
601 # From an internal working value
602 if isinstance(value, _WorkRep):
603 self._sign = value.sign
604 self._int = str(value.int)
605 self._exp = int(value.exp)
606 self._is_special = False
607 return self
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value, (list,tuple)):
611 if len(value) != 3:
612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
620 self._sign = value[0]
621 if value[2] == 'F':
622 # infinity: value[1] is ignored
623 self._int = '0'
624 self._exp = value[2]
625 self._is_special = True
626 else:
627 # process and validate the digits in value[1]
628 digits = []
629 for digit in value[1]:
630 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
631 # skip leading zeros
632 if digits or digit != 0:
633 digits.append(digit)
634 else:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
637 "0 through 9.")
638 if value[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
640 self._int = ''.join(map(str, digits))
641 self._exp = value[2]
642 self._is_special = True
643 elif isinstance(value[2], (int, long)):
644 # finite number: digits give the coefficient
645 self._int = ''.join(map(str, digits or [0]))
646 self._exp = value[2]
647 self._is_special = False
648 else:
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
652 return self
654 if isinstance(value, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
658 raise TypeError("Cannot convert %r to Decimal" % value)
660 def _isnan(self):
661 """Returns whether the number is not actually one.
663 0 if a number
664 1 if NaN
665 2 if sNaN
667 if self._is_special:
668 exp = self._exp
669 if exp == 'n':
670 return 1
671 elif exp == 'N':
672 return 2
673 return 0
675 def _isinfinity(self):
676 """Returns whether the number is infinite
678 0 if finite or not a number
679 1 if +INF
680 -1 if -INF
682 if self._exp == 'F':
683 if self._sign:
684 return -1
685 return 1
686 return 0
688 def _check_nans(self, other=None, context=None):
689 """Returns whether the number is not actually one.
691 if self, other are sNaN, signal
692 if self, other are NaN return nan
693 return 0
695 Done before operations.
698 self_is_nan = self._isnan()
699 if other is None:
700 other_is_nan = False
701 else:
702 other_is_nan = other._isnan()
704 if self_is_nan or other_is_nan:
705 if context is None:
706 context = getcontext()
708 if self_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
710 self)
711 if other_is_nan == 2:
712 return context._raise_error(InvalidOperation, 'sNaN',
713 other)
714 if self_is_nan:
715 return self._fix_nan(context)
717 return other._fix_nan(context)
718 return 0
720 def __nonzero__(self):
721 """Return True if self is nonzero; otherwise return False.
723 NaNs and infinities are considered nonzero.
725 return self._is_special or self._int != '0'
727 def __cmp__(self, other):
728 other = _convert_other(other)
729 if other is NotImplemented:
730 # Never return NotImplemented
731 return 1
733 if self._is_special or other._is_special:
734 # check for nans, without raising on a signaling nan
735 if self._isnan() or other._isnan():
736 return 1 # Comparison involving NaN's always reports self > other
738 # INF = INF
739 return cmp(self._isinfinity(), other._isinfinity())
741 # check for zeros; note that cmp(0, -0) should return 0
742 if not self:
743 if not other:
744 return 0
745 else:
746 return -((-1)**other._sign)
747 if not other:
748 return (-1)**self._sign
750 # If different signs, neg one is less
751 if other._sign < self._sign:
752 return -1
753 if self._sign < other._sign:
754 return 1
756 self_adjusted = self.adjusted()
757 other_adjusted = other.adjusted()
758 if self_adjusted == other_adjusted:
759 self_padded = self._int + '0'*(self._exp - other._exp)
760 other_padded = other._int + '0'*(other._exp - self._exp)
761 return cmp(self_padded, other_padded) * (-1)**self._sign
762 elif self_adjusted > other_adjusted:
763 return (-1)**self._sign
764 else: # self_adjusted < other_adjusted
765 return -((-1)**self._sign)
767 def __eq__(self, other):
768 if not isinstance(other, (Decimal, int, long)):
769 return NotImplemented
770 return self.__cmp__(other) == 0
772 def __ne__(self, other):
773 if not isinstance(other, (Decimal, int, long)):
774 return NotImplemented
775 return self.__cmp__(other) != 0
777 def compare(self, other, context=None):
778 """Compares one to another.
780 -1 => a < b
781 0 => a = b
782 1 => a > b
783 NaN => one is NaN
784 Like __cmp__, but returns Decimal instances.
786 other = _convert_other(other, raiseit=True)
788 # Compare(NaN, NaN) = NaN
789 if (self._is_special or other and other._is_special):
790 ans = self._check_nans(other, context)
791 if ans:
792 return ans
794 return Decimal(self.__cmp__(other))
796 def __hash__(self):
797 """x.__hash__() <==> hash(x)"""
798 # Decimal integers must hash the same as the ints
800 # The hash of a nonspecial noninteger Decimal must depend only
801 # on the value of that Decimal, and not on its representation.
802 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
803 if self._is_special:
804 if self._isnan():
805 raise TypeError('Cannot hash a NaN value.')
806 return hash(str(self))
807 if not self:
808 return 0
809 if self._isinteger():
810 op = _WorkRep(self.to_integral_value())
811 # to make computation feasible for Decimals with large
812 # exponent, we use the fact that hash(n) == hash(m) for
813 # any two nonzero integers n and m such that (i) n and m
814 # have the same sign, and (ii) n is congruent to m modulo
815 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
816 # hash((-1)**s*c*pow(10, e, 2**64-1).
817 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
818 # The value of a nonzero nonspecial Decimal instance is
819 # faithfully represented by the triple consisting of its sign,
820 # its adjusted exponent, and its coefficient with trailing
821 # zeros removed.
822 return hash((self._sign,
823 self._exp+len(self._int),
824 self._int.rstrip('0')))
826 def as_tuple(self):
827 """Represents the number as a triple tuple.
829 To show the internals exactly as they are.
831 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
833 def __repr__(self):
834 """Represents the number as an instance of Decimal."""
835 # Invariant: eval(repr(d)) == d
836 return 'Decimal("%s")' % str(self)
838 def __str__(self, eng=False, context=None):
839 """Return string representation of the number in scientific notation.
841 Captures all of the information in the underlying representation.
844 sign = ['', '-'][self._sign]
845 if self._is_special:
846 if self._exp == 'F':
847 return sign + 'Infinity'
848 elif self._exp == 'n':
849 return sign + 'NaN' + self._int
850 else: # self._exp == 'N'
851 return sign + 'sNaN' + self._int
853 # number of digits of self._int to left of decimal point
854 leftdigits = self._exp + len(self._int)
856 # dotplace is number of digits of self._int to the left of the
857 # decimal point in the mantissa of the output string (that is,
858 # after adjusting the exponent)
859 if self._exp <= 0 and leftdigits > -6:
860 # no exponent required
861 dotplace = leftdigits
862 elif not eng:
863 # usual scientific notation: 1 digit on left of the point
864 dotplace = 1
865 elif self._int == '0':
866 # engineering notation, zero
867 dotplace = (leftdigits + 1) % 3 - 1
868 else:
869 # engineering notation, nonzero
870 dotplace = (leftdigits - 1) % 3 + 1
872 if dotplace <= 0:
873 intpart = '0'
874 fracpart = '.' + '0'*(-dotplace) + self._int
875 elif dotplace >= len(self._int):
876 intpart = self._int+'0'*(dotplace-len(self._int))
877 fracpart = ''
878 else:
879 intpart = self._int[:dotplace]
880 fracpart = '.' + self._int[dotplace:]
881 if leftdigits == dotplace:
882 exp = ''
883 else:
884 if context is None:
885 context = getcontext()
886 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
888 return sign + intpart + fracpart + exp
890 def to_eng_string(self, context=None):
891 """Convert to engineering-type string.
893 Engineering notation has an exponent which is a multiple of 3, so there
894 are up to 3 digits left of the decimal place.
896 Same rules for when in exponential and when as a value as in __str__.
898 return self.__str__(eng=True, context=context)
900 def __neg__(self, context=None):
901 """Returns a copy with the sign switched.
903 Rounds, if it has reason.
905 if self._is_special:
906 ans = self._check_nans(context=context)
907 if ans:
908 return ans
910 if not self:
911 # -Decimal('0') is Decimal('0'), not Decimal('-0')
912 ans = self.copy_abs()
913 else:
914 ans = self.copy_negate()
916 if context is None:
917 context = getcontext()
918 return ans._fix(context)
920 def __pos__(self, context=None):
921 """Returns a copy, unless it is a sNaN.
923 Rounds the number (if more then precision digits)
925 if self._is_special:
926 ans = self._check_nans(context=context)
927 if ans:
928 return ans
930 if not self:
931 # + (-0) = 0
932 ans = self.copy_abs()
933 else:
934 ans = Decimal(self)
936 if context is None:
937 context = getcontext()
938 return ans._fix(context)
940 def __abs__(self, round=True, context=None):
941 """Returns the absolute value of self.
943 If the keyword argument 'round' is false, do not round. The
944 expression self.__abs__(round=False) is equivalent to
945 self.copy_abs().
947 if not round:
948 return self.copy_abs()
950 if self._is_special:
951 ans = self._check_nans(context=context)
952 if ans:
953 return ans
955 if self._sign:
956 ans = self.__neg__(context=context)
957 else:
958 ans = self.__pos__(context=context)
960 return ans
962 def __add__(self, other, context=None):
963 """Returns self + other.
965 -INF + INF (or the reverse) cause InvalidOperation errors.
967 other = _convert_other(other)
968 if other is NotImplemented:
969 return other
971 if context is None:
972 context = getcontext()
974 if self._is_special or other._is_special:
975 ans = self._check_nans(other, context)
976 if ans:
977 return ans
979 if self._isinfinity():
980 # If both INF, same sign => same as both, opposite => error.
981 if self._sign != other._sign and other._isinfinity():
982 return context._raise_error(InvalidOperation, '-INF + INF')
983 return Decimal(self)
984 if other._isinfinity():
985 return Decimal(other) # Can't both be infinity here
987 exp = min(self._exp, other._exp)
988 negativezero = 0
989 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
990 # If the answer is 0, the sign should be negative, in this case.
991 negativezero = 1
993 if not self and not other:
994 sign = min(self._sign, other._sign)
995 if negativezero:
996 sign = 1
997 ans = _dec_from_triple(sign, '0', exp)
998 ans = ans._fix(context)
999 return ans
1000 if not self:
1001 exp = max(exp, other._exp - context.prec-1)
1002 ans = other._rescale(exp, context.rounding)
1003 ans = ans._fix(context)
1004 return ans
1005 if not other:
1006 exp = max(exp, self._exp - context.prec-1)
1007 ans = self._rescale(exp, context.rounding)
1008 ans = ans._fix(context)
1009 return ans
1011 op1 = _WorkRep(self)
1012 op2 = _WorkRep(other)
1013 op1, op2 = _normalize(op1, op2, context.prec)
1015 result = _WorkRep()
1016 if op1.sign != op2.sign:
1017 # Equal and opposite
1018 if op1.int == op2.int:
1019 ans = _dec_from_triple(negativezero, '0', exp)
1020 ans = ans._fix(context)
1021 return ans
1022 if op1.int < op2.int:
1023 op1, op2 = op2, op1
1024 # OK, now abs(op1) > abs(op2)
1025 if op1.sign == 1:
1026 result.sign = 1
1027 op1.sign, op2.sign = op2.sign, op1.sign
1028 else:
1029 result.sign = 0
1030 # So we know the sign, and op1 > 0.
1031 elif op1.sign == 1:
1032 result.sign = 1
1033 op1.sign, op2.sign = (0, 0)
1034 else:
1035 result.sign = 0
1036 # Now, op1 > abs(op2) > 0
1038 if op2.sign == 0:
1039 result.int = op1.int + op2.int
1040 else:
1041 result.int = op1.int - op2.int
1043 result.exp = op1.exp
1044 ans = Decimal(result)
1045 ans = ans._fix(context)
1046 return ans
1048 __radd__ = __add__
1050 def __sub__(self, other, context=None):
1051 """Return self - other"""
1052 other = _convert_other(other)
1053 if other is NotImplemented:
1054 return other
1056 if self._is_special or other._is_special:
1057 ans = self._check_nans(other, context=context)
1058 if ans:
1059 return ans
1061 # self - other is computed as self + other.copy_negate()
1062 return self.__add__(other.copy_negate(), context=context)
1064 def __rsub__(self, other, context=None):
1065 """Return other - self"""
1066 other = _convert_other(other)
1067 if other is NotImplemented:
1068 return other
1070 return other.__sub__(self, context=context)
1072 def __mul__(self, other, context=None):
1073 """Return self * other.
1075 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1077 other = _convert_other(other)
1078 if other is NotImplemented:
1079 return other
1081 if context is None:
1082 context = getcontext()
1084 resultsign = self._sign ^ other._sign
1086 if self._is_special or other._is_special:
1087 ans = self._check_nans(other, context)
1088 if ans:
1089 return ans
1091 if self._isinfinity():
1092 if not other:
1093 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1094 return Infsign[resultsign]
1096 if other._isinfinity():
1097 if not self:
1098 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1099 return Infsign[resultsign]
1101 resultexp = self._exp + other._exp
1103 # Special case for multiplying by zero
1104 if not self or not other:
1105 ans = _dec_from_triple(resultsign, '0', resultexp)
1106 # Fixing in case the exponent is out of bounds
1107 ans = ans._fix(context)
1108 return ans
1110 # Special case for multiplying by power of 10
1111 if self._int == '1':
1112 ans = _dec_from_triple(resultsign, other._int, resultexp)
1113 ans = ans._fix(context)
1114 return ans
1115 if other._int == '1':
1116 ans = _dec_from_triple(resultsign, self._int, resultexp)
1117 ans = ans._fix(context)
1118 return ans
1120 op1 = _WorkRep(self)
1121 op2 = _WorkRep(other)
1123 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1124 ans = ans._fix(context)
1126 return ans
1127 __rmul__ = __mul__
1129 def __div__(self, other, context=None):
1130 """Return self / other."""
1131 other = _convert_other(other)
1132 if other is NotImplemented:
1133 return NotImplemented
1135 if context is None:
1136 context = getcontext()
1138 sign = self._sign ^ other._sign
1140 if self._is_special or other._is_special:
1141 ans = self._check_nans(other, context)
1142 if ans:
1143 return ans
1145 if self._isinfinity() and other._isinfinity():
1146 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1148 if self._isinfinity():
1149 return Infsign[sign]
1151 if other._isinfinity():
1152 context._raise_error(Clamped, 'Division by infinity')
1153 return _dec_from_triple(sign, '0', context.Etiny())
1155 # Special cases for zeroes
1156 if not other:
1157 if not self:
1158 return context._raise_error(DivisionUndefined, '0 / 0')
1159 return context._raise_error(DivisionByZero, 'x / 0', sign)
1161 if not self:
1162 exp = self._exp - other._exp
1163 coeff = 0
1164 else:
1165 # OK, so neither = 0, INF or NaN
1166 shift = len(other._int) - len(self._int) + context.prec + 1
1167 exp = self._exp - other._exp - shift
1168 op1 = _WorkRep(self)
1169 op2 = _WorkRep(other)
1170 if shift >= 0:
1171 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1172 else:
1173 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1174 if remainder:
1175 # result is not exact; adjust to ensure correct rounding
1176 if coeff % 5 == 0:
1177 coeff += 1
1178 else:
1179 # result is exact; get as close to ideal exponent as possible
1180 ideal_exp = self._exp - other._exp
1181 while exp < ideal_exp and coeff % 10 == 0:
1182 coeff //= 10
1183 exp += 1
1185 ans = _dec_from_triple(sign, str(coeff), exp)
1186 return ans._fix(context)
1188 __truediv__ = __div__
1190 def _divide(self, other, context):
1191 """Return (self // other, self % other), to context.prec precision.
1193 Assumes that neither self nor other is a NaN, that self is not
1194 infinite and that other is nonzero.
1196 sign = self._sign ^ other._sign
1197 if other._isinfinity():
1198 ideal_exp = self._exp
1199 else:
1200 ideal_exp = min(self._exp, other._exp)
1202 expdiff = self.adjusted() - other.adjusted()
1203 if not self or other._isinfinity() or expdiff <= -2:
1204 return (_dec_from_triple(sign, '0', 0),
1205 self._rescale(ideal_exp, context.rounding))
1206 if expdiff <= context.prec:
1207 op1 = _WorkRep(self)
1208 op2 = _WorkRep(other)
1209 if op1.exp >= op2.exp:
1210 op1.int *= 10**(op1.exp - op2.exp)
1211 else:
1212 op2.int *= 10**(op2.exp - op1.exp)
1213 q, r = divmod(op1.int, op2.int)
1214 if q < 10**context.prec:
1215 return (_dec_from_triple(sign, str(q), 0),
1216 _dec_from_triple(self._sign, str(r), ideal_exp))
1218 # Here the quotient is too large to be representable
1219 ans = context._raise_error(DivisionImpossible,
1220 'quotient too large in //, % or divmod')
1221 return ans, ans
1223 def __rdiv__(self, other, context=None):
1224 """Swaps self/other and returns __div__."""
1225 other = _convert_other(other)
1226 if other is NotImplemented:
1227 return other
1228 return other.__div__(self, context=context)
1229 __rtruediv__ = __rdiv__
1231 def __divmod__(self, other, context=None):
1233 Return (self // other, self % other)
1235 other = _convert_other(other)
1236 if other is NotImplemented:
1237 return other
1239 if context is None:
1240 context = getcontext()
1242 ans = self._check_nans(other, context)
1243 if ans:
1244 return (ans, ans)
1246 sign = self._sign ^ other._sign
1247 if self._isinfinity():
1248 if other._isinfinity():
1249 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1250 return ans, ans
1251 else:
1252 return (Infsign[sign],
1253 context._raise_error(InvalidOperation, 'INF % x'))
1255 if not other:
1256 if not self:
1257 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1258 return ans, ans
1259 else:
1260 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1261 context._raise_error(InvalidOperation, 'x % 0'))
1263 quotient, remainder = self._divide(other, context)
1264 remainder = remainder._fix(context)
1265 return quotient, remainder
1267 def __rdivmod__(self, other, context=None):
1268 """Swaps self/other and returns __divmod__."""
1269 other = _convert_other(other)
1270 if other is NotImplemented:
1271 return other
1272 return other.__divmod__(self, context=context)
1274 def __mod__(self, other, context=None):
1276 self % other
1278 other = _convert_other(other)
1279 if other is NotImplemented:
1280 return other
1282 if context is None:
1283 context = getcontext()
1285 ans = self._check_nans(other, context)
1286 if ans:
1287 return ans
1289 if self._isinfinity():
1290 return context._raise_error(InvalidOperation, 'INF % x')
1291 elif not other:
1292 if self:
1293 return context._raise_error(InvalidOperation, 'x % 0')
1294 else:
1295 return context._raise_error(DivisionUndefined, '0 % 0')
1297 remainder = self._divide(other, context)[1]
1298 remainder = remainder._fix(context)
1299 return remainder
1301 def __rmod__(self, other, context=None):
1302 """Swaps self/other and returns __mod__."""
1303 other = _convert_other(other)
1304 if other is NotImplemented:
1305 return other
1306 return other.__mod__(self, context=context)
1308 def remainder_near(self, other, context=None):
1310 Remainder nearest to 0- abs(remainder-near) <= other/2
1312 if context is None:
1313 context = getcontext()
1315 other = _convert_other(other, raiseit=True)
1317 ans = self._check_nans(other, context)
1318 if ans:
1319 return ans
1321 # self == +/-infinity -> InvalidOperation
1322 if self._isinfinity():
1323 return context._raise_error(InvalidOperation,
1324 'remainder_near(infinity, x)')
1326 # other == 0 -> either InvalidOperation or DivisionUndefined
1327 if not other:
1328 if self:
1329 return context._raise_error(InvalidOperation,
1330 'remainder_near(x, 0)')
1331 else:
1332 return context._raise_error(DivisionUndefined,
1333 'remainder_near(0, 0)')
1335 # other = +/-infinity -> remainder = self
1336 if other._isinfinity():
1337 ans = Decimal(self)
1338 return ans._fix(context)
1340 # self = 0 -> remainder = self, with ideal exponent
1341 ideal_exponent = min(self._exp, other._exp)
1342 if not self:
1343 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1344 return ans._fix(context)
1346 # catch most cases of large or small quotient
1347 expdiff = self.adjusted() - other.adjusted()
1348 if expdiff >= context.prec + 1:
1349 # expdiff >= prec+1 => abs(self/other) > 10**prec
1350 return context._raise_error(DivisionImpossible)
1351 if expdiff <= -2:
1352 # expdiff <= -2 => abs(self/other) < 0.1
1353 ans = self._rescale(ideal_exponent, context.rounding)
1354 return ans._fix(context)
1356 # adjust both arguments to have the same exponent, then divide
1357 op1 = _WorkRep(self)
1358 op2 = _WorkRep(other)
1359 if op1.exp >= op2.exp:
1360 op1.int *= 10**(op1.exp - op2.exp)
1361 else:
1362 op2.int *= 10**(op2.exp - op1.exp)
1363 q, r = divmod(op1.int, op2.int)
1364 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1365 # 10**ideal_exponent. Apply correction to ensure that
1366 # abs(remainder) <= abs(other)/2
1367 if 2*r + (q&1) > op2.int:
1368 r -= op2.int
1369 q += 1
1371 if q >= 10**context.prec:
1372 return context._raise_error(DivisionImpossible)
1374 # result has same sign as self unless r is negative
1375 sign = self._sign
1376 if r < 0:
1377 sign = 1-sign
1378 r = -r
1380 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1381 return ans._fix(context)
1383 def __floordiv__(self, other, context=None):
1384 """self // other"""
1385 other = _convert_other(other)
1386 if other is NotImplemented:
1387 return other
1389 if context is None:
1390 context = getcontext()
1392 ans = self._check_nans(other, context)
1393 if ans:
1394 return ans
1396 if self._isinfinity():
1397 if other._isinfinity():
1398 return context._raise_error(InvalidOperation, 'INF // INF')
1399 else:
1400 return Infsign[self._sign ^ other._sign]
1402 if not other:
1403 if self:
1404 return context._raise_error(DivisionByZero, 'x // 0',
1405 self._sign ^ other._sign)
1406 else:
1407 return context._raise_error(DivisionUndefined, '0 // 0')
1409 return self._divide(other, context)[0]
1411 def __rfloordiv__(self, other, context=None):
1412 """Swaps self/other and returns __floordiv__."""
1413 other = _convert_other(other)
1414 if other is NotImplemented:
1415 return other
1416 return other.__floordiv__(self, context=context)
1418 def __float__(self):
1419 """Float representation."""
1420 return float(str(self))
1422 def __int__(self):
1423 """Converts self to an int, truncating if necessary."""
1424 if self._is_special:
1425 if self._isnan():
1426 context = getcontext()
1427 return context._raise_error(InvalidContext)
1428 elif self._isinfinity():
1429 raise OverflowError("Cannot convert infinity to long")
1430 s = (-1)**self._sign
1431 if self._exp >= 0:
1432 return s*int(self._int)*10**self._exp
1433 else:
1434 return s*int(self._int[:self._exp] or '0')
1436 def __long__(self):
1437 """Converts to a long.
1439 Equivalent to long(int(self))
1441 return long(self.__int__())
1443 def _fix_nan(self, context):
1444 """Decapitate the payload of a NaN to fit the context"""
1445 payload = self._int
1447 # maximum length of payload is precision if _clamp=0,
1448 # precision-1 if _clamp=1.
1449 max_payload_len = context.prec - context._clamp
1450 if len(payload) > max_payload_len:
1451 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1452 return _dec_from_triple(self._sign, payload, self._exp, True)
1453 return Decimal(self)
1455 def _fix(self, context):
1456 """Round if it is necessary to keep self within prec precision.
1458 Rounds and fixes the exponent. Does not raise on a sNaN.
1460 Arguments:
1461 self - Decimal instance
1462 context - context used.
1465 if self._is_special:
1466 if self._isnan():
1467 # decapitate payload if necessary
1468 return self._fix_nan(context)
1469 else:
1470 # self is +/-Infinity; return unaltered
1471 return Decimal(self)
1473 # if self is zero then exponent should be between Etiny and
1474 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1475 Etiny = context.Etiny()
1476 Etop = context.Etop()
1477 if not self:
1478 exp_max = [context.Emax, Etop][context._clamp]
1479 new_exp = min(max(self._exp, Etiny), exp_max)
1480 if new_exp != self._exp:
1481 context._raise_error(Clamped)
1482 return _dec_from_triple(self._sign, '0', new_exp)
1483 else:
1484 return Decimal(self)
1486 # exp_min is the smallest allowable exponent of the result,
1487 # equal to max(self.adjusted()-context.prec+1, Etiny)
1488 exp_min = len(self._int) + self._exp - context.prec
1489 if exp_min > Etop:
1490 # overflow: exp_min > Etop iff self.adjusted() > Emax
1491 context._raise_error(Inexact)
1492 context._raise_error(Rounded)
1493 return context._raise_error(Overflow, 'above Emax', self._sign)
1494 self_is_subnormal = exp_min < Etiny
1495 if self_is_subnormal:
1496 context._raise_error(Subnormal)
1497 exp_min = Etiny
1499 # round if self has too many digits
1500 if self._exp < exp_min:
1501 context._raise_error(Rounded)
1502 digits = len(self._int) + self._exp - exp_min
1503 if digits < 0:
1504 self = _dec_from_triple(self._sign, '1', exp_min-1)
1505 digits = 0
1506 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1507 changed = this_function(digits)
1508 coeff = self._int[:digits] or '0'
1509 if changed == 1:
1510 coeff = str(int(coeff)+1)
1511 ans = _dec_from_triple(self._sign, coeff, exp_min)
1513 if changed:
1514 context._raise_error(Inexact)
1515 if self_is_subnormal:
1516 context._raise_error(Underflow)
1517 if not ans:
1518 # raise Clamped on underflow to 0
1519 context._raise_error(Clamped)
1520 elif len(ans._int) == context.prec+1:
1521 # we get here only if rescaling rounds the
1522 # cofficient up to exactly 10**context.prec
1523 if ans._exp < Etop:
1524 ans = _dec_from_triple(ans._sign,
1525 ans._int[:-1], ans._exp+1)
1526 else:
1527 # Inexact and Rounded have already been raised
1528 ans = context._raise_error(Overflow, 'above Emax',
1529 self._sign)
1530 return ans
1532 # fold down if _clamp == 1 and self has too few digits
1533 if context._clamp == 1 and self._exp > Etop:
1534 context._raise_error(Clamped)
1535 self_padded = self._int + '0'*(self._exp - Etop)
1536 return _dec_from_triple(self._sign, self_padded, Etop)
1538 # here self was representable to begin with; return unchanged
1539 return Decimal(self)
1541 _pick_rounding_function = {}
1543 # for each of the rounding functions below:
1544 # self is a finite, nonzero Decimal
1545 # prec is an integer satisfying 0 <= prec < len(self._int)
1547 # each function returns either -1, 0, or 1, as follows:
1548 # 1 indicates that self should be rounded up (away from zero)
1549 # 0 indicates that self should be truncated, and that all the
1550 # digits to be truncated are zeros (so the value is unchanged)
1551 # -1 indicates that there are nonzero digits to be truncated
1553 def _round_down(self, prec):
1554 """Also known as round-towards-0, truncate."""
1555 if _all_zeros(self._int, prec):
1556 return 0
1557 else:
1558 return -1
1560 def _round_up(self, prec):
1561 """Rounds away from 0."""
1562 return -self._round_down(prec)
1564 def _round_half_up(self, prec):
1565 """Rounds 5 up (away from 0)"""
1566 if self._int[prec] in '56789':
1567 return 1
1568 elif _all_zeros(self._int, prec):
1569 return 0
1570 else:
1571 return -1
1573 def _round_half_down(self, prec):
1574 """Round 5 down"""
1575 if _exact_half(self._int, prec):
1576 return -1
1577 else:
1578 return self._round_half_up(prec)
1580 def _round_half_even(self, prec):
1581 """Round 5 to even, rest to nearest."""
1582 if _exact_half(self._int, prec) and \
1583 (prec == 0 or self._int[prec-1] in '02468'):
1584 return -1
1585 else:
1586 return self._round_half_up(prec)
1588 def _round_ceiling(self, prec):
1589 """Rounds up (not away from 0 if negative.)"""
1590 if self._sign:
1591 return self._round_down(prec)
1592 else:
1593 return -self._round_down(prec)
1595 def _round_floor(self, prec):
1596 """Rounds down (not towards 0 if negative)"""
1597 if not self._sign:
1598 return self._round_down(prec)
1599 else:
1600 return -self._round_down(prec)
1602 def _round_05up(self, prec):
1603 """Round down unless digit prec-1 is 0 or 5."""
1604 if prec and self._int[prec-1] not in '05':
1605 return self._round_down(prec)
1606 else:
1607 return -self._round_down(prec)
1609 def fma(self, other, third, context=None):
1610 """Fused multiply-add.
1612 Returns self*other+third with no rounding of the intermediate
1613 product self*other.
1615 self and other are multiplied together, with no rounding of
1616 the result. The third operand is then added to the result,
1617 and a single final rounding is performed.
1620 other = _convert_other(other, raiseit=True)
1622 # compute product; raise InvalidOperation if either operand is
1623 # a signaling NaN or if the product is zero times infinity.
1624 if self._is_special or other._is_special:
1625 if context is None:
1626 context = getcontext()
1627 if self._exp == 'N':
1628 return context._raise_error(InvalidOperation, 'sNaN', self)
1629 if other._exp == 'N':
1630 return context._raise_error(InvalidOperation, 'sNaN', other)
1631 if self._exp == 'n':
1632 product = self
1633 elif other._exp == 'n':
1634 product = other
1635 elif self._exp == 'F':
1636 if not other:
1637 return context._raise_error(InvalidOperation,
1638 'INF * 0 in fma')
1639 product = Infsign[self._sign ^ other._sign]
1640 elif other._exp == 'F':
1641 if not self:
1642 return context._raise_error(InvalidOperation,
1643 '0 * INF in fma')
1644 product = Infsign[self._sign ^ other._sign]
1645 else:
1646 product = _dec_from_triple(self._sign ^ other._sign,
1647 str(int(self._int) * int(other._int)),
1648 self._exp + other._exp)
1650 third = _convert_other(third, raiseit=True)
1651 return product.__add__(third, context)
1653 def _power_modulo(self, other, modulo, context=None):
1654 """Three argument version of __pow__"""
1656 # if can't convert other and modulo to Decimal, raise
1657 # TypeError; there's no point returning NotImplemented (no
1658 # equivalent of __rpow__ for three argument pow)
1659 other = _convert_other(other, raiseit=True)
1660 modulo = _convert_other(modulo, raiseit=True)
1662 if context is None:
1663 context = getcontext()
1665 # deal with NaNs: if there are any sNaNs then first one wins,
1666 # (i.e. behaviour for NaNs is identical to that of fma)
1667 self_is_nan = self._isnan()
1668 other_is_nan = other._isnan()
1669 modulo_is_nan = modulo._isnan()
1670 if self_is_nan or other_is_nan or modulo_is_nan:
1671 if self_is_nan == 2:
1672 return context._raise_error(InvalidOperation, 'sNaN',
1673 self)
1674 if other_is_nan == 2:
1675 return context._raise_error(InvalidOperation, 'sNaN',
1676 other)
1677 if modulo_is_nan == 2:
1678 return context._raise_error(InvalidOperation, 'sNaN',
1679 modulo)
1680 if self_is_nan:
1681 return self._fix_nan(context)
1682 if other_is_nan:
1683 return other._fix_nan(context)
1684 return modulo._fix_nan(context)
1686 # check inputs: we apply same restrictions as Python's pow()
1687 if not (self._isinteger() and
1688 other._isinteger() and
1689 modulo._isinteger()):
1690 return context._raise_error(InvalidOperation,
1691 'pow() 3rd argument not allowed '
1692 'unless all arguments are integers')
1693 if other < 0:
1694 return context._raise_error(InvalidOperation,
1695 'pow() 2nd argument cannot be '
1696 'negative when 3rd argument specified')
1697 if not modulo:
1698 return context._raise_error(InvalidOperation,
1699 'pow() 3rd argument cannot be 0')
1701 # additional restriction for decimal: the modulus must be less
1702 # than 10**prec in absolute value
1703 if modulo.adjusted() >= context.prec:
1704 return context._raise_error(InvalidOperation,
1705 'insufficient precision: pow() 3rd '
1706 'argument must not have more than '
1707 'precision digits')
1709 # define 0**0 == NaN, for consistency with two-argument pow
1710 # (even though it hurts!)
1711 if not other and not self:
1712 return context._raise_error(InvalidOperation,
1713 'at least one of pow() 1st argument '
1714 'and 2nd argument must be nonzero ;'
1715 '0**0 is not defined')
1717 # compute sign of result
1718 if other._iseven():
1719 sign = 0
1720 else:
1721 sign = self._sign
1723 # convert modulo to a Python integer, and self and other to
1724 # Decimal integers (i.e. force their exponents to be >= 0)
1725 modulo = abs(int(modulo))
1726 base = _WorkRep(self.to_integral_value())
1727 exponent = _WorkRep(other.to_integral_value())
1729 # compute result using integer pow()
1730 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1731 for i in xrange(exponent.exp):
1732 base = pow(base, 10, modulo)
1733 base = pow(base, exponent.int, modulo)
1735 return _dec_from_triple(sign, str(base), 0)
1737 def _power_exact(self, other, p):
1738 """Attempt to compute self**other exactly.
1740 Given Decimals self and other and an integer p, attempt to
1741 compute an exact result for the power self**other, with p
1742 digits of precision. Return None if self**other is not
1743 exactly representable in p digits.
1745 Assumes that elimination of special cases has already been
1746 performed: self and other must both be nonspecial; self must
1747 be positive and not numerically equal to 1; other must be
1748 nonzero. For efficiency, other._exp should not be too large,
1749 so that 10**abs(other._exp) is a feasible calculation."""
1751 # In the comments below, we write x for the value of self and
1752 # y for the value of other. Write x = xc*10**xe and y =
1753 # yc*10**ye.
1755 # The main purpose of this method is to identify the *failure*
1756 # of x**y to be exactly representable with as little effort as
1757 # possible. So we look for cheap and easy tests that
1758 # eliminate the possibility of x**y being exact. Only if all
1759 # these tests are passed do we go on to actually compute x**y.
1761 # Here's the main idea. First normalize both x and y. We
1762 # express y as a rational m/n, with m and n relatively prime
1763 # and n>0. Then for x**y to be exactly representable (at
1764 # *any* precision), xc must be the nth power of a positive
1765 # integer and xe must be divisible by n. If m is negative
1766 # then additionally xc must be a power of either 2 or 5, hence
1767 # a power of 2**n or 5**n.
1769 # There's a limit to how small |y| can be: if y=m/n as above
1770 # then:
1772 # (1) if xc != 1 then for the result to be representable we
1773 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1774 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1775 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1776 # representable.
1778 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1779 # |y| < 1/|xe| then the result is not representable.
1781 # Note that since x is not equal to 1, at least one of (1) and
1782 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1783 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1785 # There's also a limit to how large y can be, at least if it's
1786 # positive: the normalized result will have coefficient xc**y,
1787 # so if it's representable then xc**y < 10**p, and y <
1788 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1789 # not exactly representable.
1791 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1792 # so |y| < 1/xe and the result is not representable.
1793 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1794 # < 1/nbits(xc).
1796 x = _WorkRep(self)
1797 xc, xe = x.int, x.exp
1798 while xc % 10 == 0:
1799 xc //= 10
1800 xe += 1
1802 y = _WorkRep(other)
1803 yc, ye = y.int, y.exp
1804 while yc % 10 == 0:
1805 yc //= 10
1806 ye += 1
1808 # case where xc == 1: result is 10**(xe*y), with xe*y
1809 # required to be an integer
1810 if xc == 1:
1811 if ye >= 0:
1812 exponent = xe*yc*10**ye
1813 else:
1814 exponent, remainder = divmod(xe*yc, 10**-ye)
1815 if remainder:
1816 return None
1817 if y.sign == 1:
1818 exponent = -exponent
1819 # if other is a nonnegative integer, use ideal exponent
1820 if other._isinteger() and other._sign == 0:
1821 ideal_exponent = self._exp*int(other)
1822 zeros = min(exponent-ideal_exponent, p-1)
1823 else:
1824 zeros = 0
1825 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1827 # case where y is negative: xc must be either a power
1828 # of 2 or a power of 5.
1829 if y.sign == 1:
1830 last_digit = xc % 10
1831 if last_digit in (2,4,6,8):
1832 # quick test for power of 2
1833 if xc & -xc != xc:
1834 return None
1835 # now xc is a power of 2; e is its exponent
1836 e = _nbits(xc)-1
1837 # find e*y and xe*y; both must be integers
1838 if ye >= 0:
1839 y_as_int = yc*10**ye
1840 e = e*y_as_int
1841 xe = xe*y_as_int
1842 else:
1843 ten_pow = 10**-ye
1844 e, remainder = divmod(e*yc, ten_pow)
1845 if remainder:
1846 return None
1847 xe, remainder = divmod(xe*yc, ten_pow)
1848 if remainder:
1849 return None
1851 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1852 return None
1853 xc = 5**e
1855 elif last_digit == 5:
1856 # e >= log_5(xc) if xc is a power of 5; we have
1857 # equality all the way up to xc=5**2658
1858 e = _nbits(xc)*28//65
1859 xc, remainder = divmod(5**e, xc)
1860 if remainder:
1861 return None
1862 while xc % 5 == 0:
1863 xc //= 5
1864 e -= 1
1865 if ye >= 0:
1866 y_as_integer = yc*10**ye
1867 e = e*y_as_integer
1868 xe = xe*y_as_integer
1869 else:
1870 ten_pow = 10**-ye
1871 e, remainder = divmod(e*yc, ten_pow)
1872 if remainder:
1873 return None
1874 xe, remainder = divmod(xe*yc, ten_pow)
1875 if remainder:
1876 return None
1877 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1878 return None
1879 xc = 2**e
1880 else:
1881 return None
1883 if xc >= 10**p:
1884 return None
1885 xe = -e-xe
1886 return _dec_from_triple(0, str(xc), xe)
1888 # now y is positive; find m and n such that y = m/n
1889 if ye >= 0:
1890 m, n = yc*10**ye, 1
1891 else:
1892 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1893 return None
1894 xc_bits = _nbits(xc)
1895 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1896 return None
1897 m, n = yc, 10**(-ye)
1898 while m % 2 == n % 2 == 0:
1899 m //= 2
1900 n //= 2
1901 while m % 5 == n % 5 == 0:
1902 m //= 5
1903 n //= 5
1905 # compute nth root of xc*10**xe
1906 if n > 1:
1907 # if 1 < xc < 2**n then xc isn't an nth power
1908 if xc != 1 and xc_bits <= n:
1909 return None
1911 xe, rem = divmod(xe, n)
1912 if rem != 0:
1913 return None
1915 # compute nth root of xc using Newton's method
1916 a = 1L << -(-_nbits(xc)//n) # initial estimate
1917 while True:
1918 q, r = divmod(xc, a**(n-1))
1919 if a <= q:
1920 break
1921 else:
1922 a = (a*(n-1) + q)//n
1923 if not (a == q and r == 0):
1924 return None
1925 xc = a
1927 # now xc*10**xe is the nth root of the original xc*10**xe
1928 # compute mth power of xc*10**xe
1930 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1931 # 10**p and the result is not representable.
1932 if xc > 1 and m > p*100//_log10_lb(xc):
1933 return None
1934 xc = xc**m
1935 xe *= m
1936 if xc > 10**p:
1937 return None
1939 # by this point the result *is* exactly representable
1940 # adjust the exponent to get as close as possible to the ideal
1941 # exponent, if necessary
1942 str_xc = str(xc)
1943 if other._isinteger() and other._sign == 0:
1944 ideal_exponent = self._exp*int(other)
1945 zeros = min(xe-ideal_exponent, p-len(str_xc))
1946 else:
1947 zeros = 0
1948 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
1950 def __pow__(self, other, modulo=None, context=None):
1951 """Return self ** other [ % modulo].
1953 With two arguments, compute self**other.
1955 With three arguments, compute (self**other) % modulo. For the
1956 three argument form, the following restrictions on the
1957 arguments hold:
1959 - all three arguments must be integral
1960 - other must be nonnegative
1961 - either self or other (or both) must be nonzero
1962 - modulo must be nonzero and must have at most p digits,
1963 where p is the context precision.
1965 If any of these restrictions is violated the InvalidOperation
1966 flag is raised.
1968 The result of pow(self, other, modulo) is identical to the
1969 result that would be obtained by computing (self**other) %
1970 modulo with unbounded precision, but is computed more
1971 efficiently. It is always exact.
1974 if modulo is not None:
1975 return self._power_modulo(other, modulo, context)
1977 other = _convert_other(other)
1978 if other is NotImplemented:
1979 return other
1981 if context is None:
1982 context = getcontext()
1984 # either argument is a NaN => result is NaN
1985 ans = self._check_nans(other, context)
1986 if ans:
1987 return ans
1989 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1990 if not other:
1991 if not self:
1992 return context._raise_error(InvalidOperation, '0 ** 0')
1993 else:
1994 return Dec_p1
1996 # result has sign 1 iff self._sign is 1 and other is an odd integer
1997 result_sign = 0
1998 if self._sign == 1:
1999 if other._isinteger():
2000 if not other._iseven():
2001 result_sign = 1
2002 else:
2003 # -ve**noninteger = NaN
2004 # (-0)**noninteger = 0**noninteger
2005 if self:
2006 return context._raise_error(InvalidOperation,
2007 'x ** y with x negative and y not an integer')
2008 # negate self, without doing any unwanted rounding
2009 self = self.copy_negate()
2011 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2012 if not self:
2013 if other._sign == 0:
2014 return _dec_from_triple(result_sign, '0', 0)
2015 else:
2016 return Infsign[result_sign]
2018 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2019 if self._isinfinity():
2020 if other._sign == 0:
2021 return Infsign[result_sign]
2022 else:
2023 return _dec_from_triple(result_sign, '0', 0)
2025 # 1**other = 1, but the choice of exponent and the flags
2026 # depend on the exponent of self, and on whether other is a
2027 # positive integer, a negative integer, or neither
2028 if self == Dec_p1:
2029 if other._isinteger():
2030 # exp = max(self._exp*max(int(other), 0),
2031 # 1-context.prec) but evaluating int(other) directly
2032 # is dangerous until we know other is small (other
2033 # could be 1e999999999)
2034 if other._sign == 1:
2035 multiplier = 0
2036 elif other > context.prec:
2037 multiplier = context.prec
2038 else:
2039 multiplier = int(other)
2041 exp = self._exp * multiplier
2042 if exp < 1-context.prec:
2043 exp = 1-context.prec
2044 context._raise_error(Rounded)
2045 else:
2046 context._raise_error(Inexact)
2047 context._raise_error(Rounded)
2048 exp = 1-context.prec
2050 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2052 # compute adjusted exponent of self
2053 self_adj = self.adjusted()
2055 # self ** infinity is infinity if self > 1, 0 if self < 1
2056 # self ** -infinity is infinity if self < 1, 0 if self > 1
2057 if other._isinfinity():
2058 if (other._sign == 0) == (self_adj < 0):
2059 return _dec_from_triple(result_sign, '0', 0)
2060 else:
2061 return Infsign[result_sign]
2063 # from here on, the result always goes through the call
2064 # to _fix at the end of this function.
2065 ans = None
2067 # crude test to catch cases of extreme overflow/underflow. If
2068 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2069 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2070 # self**other >= 10**(Emax+1), so overflow occurs. The test
2071 # for underflow is similar.
2072 bound = self._log10_exp_bound() + other.adjusted()
2073 if (self_adj >= 0) == (other._sign == 0):
2074 # self > 1 and other +ve, or self < 1 and other -ve
2075 # possibility of overflow
2076 if bound >= len(str(context.Emax)):
2077 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2078 else:
2079 # self > 1 and other -ve, or self < 1 and other +ve
2080 # possibility of underflow to 0
2081 Etiny = context.Etiny()
2082 if bound >= len(str(-Etiny)):
2083 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2085 # try for an exact result with precision +1
2086 if ans is None:
2087 ans = self._power_exact(other, context.prec + 1)
2088 if ans is not None and result_sign == 1:
2089 ans = _dec_from_triple(1, ans._int, ans._exp)
2091 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2092 if ans is None:
2093 p = context.prec
2094 x = _WorkRep(self)
2095 xc, xe = x.int, x.exp
2096 y = _WorkRep(other)
2097 yc, ye = y.int, y.exp
2098 if y.sign == 1:
2099 yc = -yc
2101 # compute correctly rounded result: start with precision +3,
2102 # then increase precision until result is unambiguously roundable
2103 extra = 3
2104 while True:
2105 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2106 if coeff % (5*10**(len(str(coeff))-p-1)):
2107 break
2108 extra += 3
2110 ans = _dec_from_triple(result_sign, str(coeff), exp)
2112 # the specification says that for non-integer other we need to
2113 # raise Inexact, even when the result is actually exact. In
2114 # the same way, we need to raise Underflow here if the result
2115 # is subnormal. (The call to _fix will take care of raising
2116 # Rounded and Subnormal, as usual.)
2117 if not other._isinteger():
2118 context._raise_error(Inexact)
2119 # pad with zeros up to length context.prec+1 if necessary
2120 if len(ans._int) <= context.prec:
2121 expdiff = context.prec+1 - len(ans._int)
2122 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2123 ans._exp-expdiff)
2124 if ans.adjusted() < context.Emin:
2125 context._raise_error(Underflow)
2127 # unlike exp, ln and log10, the power function respects the
2128 # rounding mode; no need to use ROUND_HALF_EVEN here
2129 ans = ans._fix(context)
2130 return ans
2132 def __rpow__(self, other, context=None):
2133 """Swaps self/other and returns __pow__."""
2134 other = _convert_other(other)
2135 if other is NotImplemented:
2136 return other
2137 return other.__pow__(self, context=context)
2139 def normalize(self, context=None):
2140 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2142 if context is None:
2143 context = getcontext()
2145 if self._is_special:
2146 ans = self._check_nans(context=context)
2147 if ans:
2148 return ans
2150 dup = self._fix(context)
2151 if dup._isinfinity():
2152 return dup
2154 if not dup:
2155 return _dec_from_triple(dup._sign, '0', 0)
2156 exp_max = [context.Emax, context.Etop()][context._clamp]
2157 end = len(dup._int)
2158 exp = dup._exp
2159 while dup._int[end-1] == '0' and exp < exp_max:
2160 exp += 1
2161 end -= 1
2162 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2164 def quantize(self, exp, rounding=None, context=None, watchexp=True):
2165 """Quantize self so its exponent is the same as that of exp.
2167 Similar to self._rescale(exp._exp) but with error checking.
2169 exp = _convert_other(exp, raiseit=True)
2171 if context is None:
2172 context = getcontext()
2173 if rounding is None:
2174 rounding = context.rounding
2176 if self._is_special or exp._is_special:
2177 ans = self._check_nans(exp, context)
2178 if ans:
2179 return ans
2181 if exp._isinfinity() or self._isinfinity():
2182 if exp._isinfinity() and self._isinfinity():
2183 return Decimal(self) # if both are inf, it is OK
2184 return context._raise_error(InvalidOperation,
2185 'quantize with one INF')
2187 # if we're not watching exponents, do a simple rescale
2188 if not watchexp:
2189 ans = self._rescale(exp._exp, rounding)
2190 # raise Inexact and Rounded where appropriate
2191 if ans._exp > self._exp:
2192 context._raise_error(Rounded)
2193 if ans != self:
2194 context._raise_error(Inexact)
2195 return ans
2197 # exp._exp should be between Etiny and Emax
2198 if not (context.Etiny() <= exp._exp <= context.Emax):
2199 return context._raise_error(InvalidOperation,
2200 'target exponent out of bounds in quantize')
2202 if not self:
2203 ans = _dec_from_triple(self._sign, '0', exp._exp)
2204 return ans._fix(context)
2206 self_adjusted = self.adjusted()
2207 if self_adjusted > context.Emax:
2208 return context._raise_error(InvalidOperation,
2209 'exponent of quantize result too large for current context')
2210 if self_adjusted - exp._exp + 1 > context.prec:
2211 return context._raise_error(InvalidOperation,
2212 'quantize result has too many digits for current context')
2214 ans = self._rescale(exp._exp, rounding)
2215 if ans.adjusted() > context.Emax:
2216 return context._raise_error(InvalidOperation,
2217 'exponent of quantize result too large for current context')
2218 if len(ans._int) > context.prec:
2219 return context._raise_error(InvalidOperation,
2220 'quantize result has too many digits for current context')
2222 # raise appropriate flags
2223 if ans._exp > self._exp:
2224 context._raise_error(Rounded)
2225 if ans != self:
2226 context._raise_error(Inexact)
2227 if ans and ans.adjusted() < context.Emin:
2228 context._raise_error(Subnormal)
2230 # call to fix takes care of any necessary folddown
2231 ans = ans._fix(context)
2232 return ans
2234 def same_quantum(self, other):
2235 """Return True if self and other have the same exponent; otherwise
2236 return False.
2238 If either operand is a special value, the following rules are used:
2239 * return True if both operands are infinities
2240 * return True if both operands are NaNs
2241 * otherwise, return False.
2243 other = _convert_other(other, raiseit=True)
2244 if self._is_special or other._is_special:
2245 return (self.is_nan() and other.is_nan() or
2246 self.is_infinite() and other.is_infinite())
2247 return self._exp == other._exp
2249 def _rescale(self, exp, rounding):
2250 """Rescale self so that the exponent is exp, either by padding with zeros
2251 or by truncating digits, using the given rounding mode.
2253 Specials are returned without change. This operation is
2254 quiet: it raises no flags, and uses no information from the
2255 context.
2257 exp = exp to scale to (an integer)
2258 rounding = rounding mode
2260 if self._is_special:
2261 return Decimal(self)
2262 if not self:
2263 return _dec_from_triple(self._sign, '0', exp)
2265 if self._exp >= exp:
2266 # pad answer with zeros if necessary
2267 return _dec_from_triple(self._sign,
2268 self._int + '0'*(self._exp - exp), exp)
2270 # too many digits; round and lose data. If self.adjusted() <
2271 # exp-1, replace self by 10**(exp-1) before rounding
2272 digits = len(self._int) + self._exp - exp
2273 if digits < 0:
2274 self = _dec_from_triple(self._sign, '1', exp-1)
2275 digits = 0
2276 this_function = getattr(self, self._pick_rounding_function[rounding])
2277 changed = this_function(digits)
2278 coeff = self._int[:digits] or '0'
2279 if changed == 1:
2280 coeff = str(int(coeff)+1)
2281 return _dec_from_triple(self._sign, coeff, exp)
2283 def to_integral_exact(self, rounding=None, context=None):
2284 """Rounds to a nearby integer.
2286 If no rounding mode is specified, take the rounding mode from
2287 the context. This method raises the Rounded and Inexact flags
2288 when appropriate.
2290 See also: to_integral_value, which does exactly the same as
2291 this method except that it doesn't raise Inexact or Rounded.
2293 if self._is_special:
2294 ans = self._check_nans(context=context)
2295 if ans:
2296 return ans
2297 return Decimal(self)
2298 if self._exp >= 0:
2299 return Decimal(self)
2300 if not self:
2301 return _dec_from_triple(self._sign, '0', 0)
2302 if context is None:
2303 context = getcontext()
2304 if rounding is None:
2305 rounding = context.rounding
2306 context._raise_error(Rounded)
2307 ans = self._rescale(0, rounding)
2308 if ans != self:
2309 context._raise_error(Inexact)
2310 return ans
2312 def to_integral_value(self, rounding=None, context=None):
2313 """Rounds to the nearest integer, without raising inexact, rounded."""
2314 if context is None:
2315 context = getcontext()
2316 if rounding is None:
2317 rounding = context.rounding
2318 if self._is_special:
2319 ans = self._check_nans(context=context)
2320 if ans:
2321 return ans
2322 return Decimal(self)
2323 if self._exp >= 0:
2324 return Decimal(self)
2325 else:
2326 return self._rescale(0, rounding)
2328 # the method name changed, but we provide also the old one, for compatibility
2329 to_integral = to_integral_value
2331 def sqrt(self, context=None):
2332 """Return the square root of self."""
2333 if self._is_special:
2334 ans = self._check_nans(context=context)
2335 if ans:
2336 return ans
2338 if self._isinfinity() and self._sign == 0:
2339 return Decimal(self)
2341 if not self:
2342 # exponent = self._exp // 2. sqrt(-0) = -0
2343 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2344 return ans._fix(context)
2346 if context is None:
2347 context = getcontext()
2349 if self._sign == 1:
2350 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2352 # At this point self represents a positive number. Let p be
2353 # the desired precision and express self in the form c*100**e
2354 # with c a positive real number and e an integer, c and e
2355 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2356 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2357 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2358 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2359 # the closest integer to sqrt(c) with the even integer chosen
2360 # in the case of a tie.
2362 # To ensure correct rounding in all cases, we use the
2363 # following trick: we compute the square root to an extra
2364 # place (precision p+1 instead of precision p), rounding down.
2365 # Then, if the result is inexact and its last digit is 0 or 5,
2366 # we increase the last digit to 1 or 6 respectively; if it's
2367 # exact we leave the last digit alone. Now the final round to
2368 # p places (or fewer in the case of underflow) will round
2369 # correctly and raise the appropriate flags.
2371 # use an extra digit of precision
2372 prec = context.prec+1
2374 # write argument in the form c*100**e where e = self._exp//2
2375 # is the 'ideal' exponent, to be used if the square root is
2376 # exactly representable. l is the number of 'digits' of c in
2377 # base 100, so that 100**(l-1) <= c < 100**l.
2378 op = _WorkRep(self)
2379 e = op.exp >> 1
2380 if op.exp & 1:
2381 c = op.int * 10
2382 l = (len(self._int) >> 1) + 1
2383 else:
2384 c = op.int
2385 l = len(self._int)+1 >> 1
2387 # rescale so that c has exactly prec base 100 'digits'
2388 shift = prec-l
2389 if shift >= 0:
2390 c *= 100**shift
2391 exact = True
2392 else:
2393 c, remainder = divmod(c, 100**-shift)
2394 exact = not remainder
2395 e -= shift
2397 # find n = floor(sqrt(c)) using Newton's method
2398 n = 10**prec
2399 while True:
2400 q = c//n
2401 if n <= q:
2402 break
2403 else:
2404 n = n + q >> 1
2405 exact = exact and n*n == c
2407 if exact:
2408 # result is exact; rescale to use ideal exponent e
2409 if shift >= 0:
2410 # assert n % 10**shift == 0
2411 n //= 10**shift
2412 else:
2413 n *= 10**-shift
2414 e += shift
2415 else:
2416 # result is not exact; fix last digit as described above
2417 if n % 5 == 0:
2418 n += 1
2420 ans = _dec_from_triple(0, str(n), e)
2422 # round, and fit to current context
2423 context = context._shallow_copy()
2424 rounding = context._set_rounding(ROUND_HALF_EVEN)
2425 ans = ans._fix(context)
2426 context.rounding = rounding
2428 return ans
2430 def max(self, other, context=None):
2431 """Returns the larger value.
2433 Like max(self, other) except if one is not a number, returns
2434 NaN (and signals if one is sNaN). Also rounds.
2436 other = _convert_other(other, raiseit=True)
2438 if context is None:
2439 context = getcontext()
2441 if self._is_special or other._is_special:
2442 # If one operand is a quiet NaN and the other is number, then the
2443 # number is always returned
2444 sn = self._isnan()
2445 on = other._isnan()
2446 if sn or on:
2447 if on == 1 and sn != 2:
2448 return self._fix_nan(context)
2449 if sn == 1 and on != 2:
2450 return other._fix_nan(context)
2451 return self._check_nans(other, context)
2453 c = self.__cmp__(other)
2454 if c == 0:
2455 # If both operands are finite and equal in numerical value
2456 # then an ordering is applied:
2458 # If the signs differ then max returns the operand with the
2459 # positive sign and min returns the operand with the negative sign
2461 # If the signs are the same then the exponent is used to select
2462 # the result. This is exactly the ordering used in compare_total.
2463 c = self.compare_total(other)
2465 if c == -1:
2466 ans = other
2467 else:
2468 ans = self
2470 return ans._fix(context)
2472 def min(self, other, context=None):
2473 """Returns the smaller value.
2475 Like min(self, other) except if one is not a number, returns
2476 NaN (and signals if one is sNaN). Also rounds.
2478 other = _convert_other(other, raiseit=True)
2480 if context is None:
2481 context = getcontext()
2483 if self._is_special or other._is_special:
2484 # If one operand is a quiet NaN and the other is number, then the
2485 # number is always returned
2486 sn = self._isnan()
2487 on = other._isnan()
2488 if sn or on:
2489 if on == 1 and sn != 2:
2490 return self._fix_nan(context)
2491 if sn == 1 and on != 2:
2492 return other._fix_nan(context)
2493 return self._check_nans(other, context)
2495 c = self.__cmp__(other)
2496 if c == 0:
2497 c = self.compare_total(other)
2499 if c == -1:
2500 ans = self
2501 else:
2502 ans = other
2504 return ans._fix(context)
2506 def _isinteger(self):
2507 """Returns whether self is an integer"""
2508 if self._is_special:
2509 return False
2510 if self._exp >= 0:
2511 return True
2512 rest = self._int[self._exp:]
2513 return rest == '0'*len(rest)
2515 def _iseven(self):
2516 """Returns True if self is even. Assumes self is an integer."""
2517 if not self or self._exp > 0:
2518 return True
2519 return self._int[-1+self._exp] in '02468'
2521 def adjusted(self):
2522 """Return the adjusted exponent of self"""
2523 try:
2524 return self._exp + len(self._int) - 1
2525 # If NaN or Infinity, self._exp is string
2526 except TypeError:
2527 return 0
2529 def canonical(self, context=None):
2530 """Returns the same Decimal object.
2532 As we do not have different encodings for the same number, the
2533 received object already is in its canonical form.
2535 return self
2537 def compare_signal(self, other, context=None):
2538 """Compares self to the other operand numerically.
2540 It's pretty much like compare(), but all NaNs signal, with signaling
2541 NaNs taking precedence over quiet NaNs.
2543 if context is None:
2544 context = getcontext()
2546 self_is_nan = self._isnan()
2547 other_is_nan = other._isnan()
2548 if self_is_nan == 2:
2549 return context._raise_error(InvalidOperation, 'sNaN',
2550 self)
2551 if other_is_nan == 2:
2552 return context._raise_error(InvalidOperation, 'sNaN',
2553 other)
2554 if self_is_nan:
2555 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2556 self)
2557 if other_is_nan:
2558 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2559 other)
2560 return self.compare(other, context=context)
2562 def compare_total(self, other):
2563 """Compares self to other using the abstract representations.
2565 This is not like the standard compare, which use their numerical
2566 value. Note that a total ordering is defined for all possible abstract
2567 representations.
2569 # if one is negative and the other is positive, it's easy
2570 if self._sign and not other._sign:
2571 return Dec_n1
2572 if not self._sign and other._sign:
2573 return Dec_p1
2574 sign = self._sign
2576 # let's handle both NaN types
2577 self_nan = self._isnan()
2578 other_nan = other._isnan()
2579 if self_nan or other_nan:
2580 if self_nan == other_nan:
2581 if self._int < other._int:
2582 if sign:
2583 return Dec_p1
2584 else:
2585 return Dec_n1
2586 if self._int > other._int:
2587 if sign:
2588 return Dec_n1
2589 else:
2590 return Dec_p1
2591 return Dec_0
2593 if sign:
2594 if self_nan == 1:
2595 return Dec_n1
2596 if other_nan == 1:
2597 return Dec_p1
2598 if self_nan == 2:
2599 return Dec_n1
2600 if other_nan == 2:
2601 return Dec_p1
2602 else:
2603 if self_nan == 1:
2604 return Dec_p1
2605 if other_nan == 1:
2606 return Dec_n1
2607 if self_nan == 2:
2608 return Dec_p1
2609 if other_nan == 2:
2610 return Dec_n1
2612 if self < other:
2613 return Dec_n1
2614 if self > other:
2615 return Dec_p1
2617 if self._exp < other._exp:
2618 if sign:
2619 return Dec_p1
2620 else:
2621 return Dec_n1
2622 if self._exp > other._exp:
2623 if sign:
2624 return Dec_n1
2625 else:
2626 return Dec_p1
2627 return Dec_0
2630 def compare_total_mag(self, other):
2631 """Compares self to other using abstract repr., ignoring sign.
2633 Like compare_total, but with operand's sign ignored and assumed to be 0.
2635 s = self.copy_abs()
2636 o = other.copy_abs()
2637 return s.compare_total(o)
2639 def copy_abs(self):
2640 """Returns a copy with the sign set to 0. """
2641 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2643 def copy_negate(self):
2644 """Returns a copy with the sign inverted."""
2645 if self._sign:
2646 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2647 else:
2648 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2650 def copy_sign(self, other):
2651 """Returns self with the sign of other."""
2652 return _dec_from_triple(other._sign, self._int,
2653 self._exp, self._is_special)
2655 def exp(self, context=None):
2656 """Returns e ** self."""
2658 if context is None:
2659 context = getcontext()
2661 # exp(NaN) = NaN
2662 ans = self._check_nans(context=context)
2663 if ans:
2664 return ans
2666 # exp(-Infinity) = 0
2667 if self._isinfinity() == -1:
2668 return Dec_0
2670 # exp(0) = 1
2671 if not self:
2672 return Dec_p1
2674 # exp(Infinity) = Infinity
2675 if self._isinfinity() == 1:
2676 return Decimal(self)
2678 # the result is now guaranteed to be inexact (the true
2679 # mathematical result is transcendental). There's no need to
2680 # raise Rounded and Inexact here---they'll always be raised as
2681 # a result of the call to _fix.
2682 p = context.prec
2683 adj = self.adjusted()
2685 # we only need to do any computation for quite a small range
2686 # of adjusted exponents---for example, -29 <= adj <= 10 for
2687 # the default context. For smaller exponent the result is
2688 # indistinguishable from 1 at the given precision, while for
2689 # larger exponent the result either overflows or underflows.
2690 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2691 # overflow
2692 ans = _dec_from_triple(0, '1', context.Emax+1)
2693 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2694 # underflow to 0
2695 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2696 elif self._sign == 0 and adj < -p:
2697 # p+1 digits; final round will raise correct flags
2698 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2699 elif self._sign == 1 and adj < -p-1:
2700 # p+1 digits; final round will raise correct flags
2701 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2702 # general case
2703 else:
2704 op = _WorkRep(self)
2705 c, e = op.int, op.exp
2706 if op.sign == 1:
2707 c = -c
2709 # compute correctly rounded result: increase precision by
2710 # 3 digits at a time until we get an unambiguously
2711 # roundable result
2712 extra = 3
2713 while True:
2714 coeff, exp = _dexp(c, e, p+extra)
2715 if coeff % (5*10**(len(str(coeff))-p-1)):
2716 break
2717 extra += 3
2719 ans = _dec_from_triple(0, str(coeff), exp)
2721 # at this stage, ans should round correctly with *any*
2722 # rounding mode, not just with ROUND_HALF_EVEN
2723 context = context._shallow_copy()
2724 rounding = context._set_rounding(ROUND_HALF_EVEN)
2725 ans = ans._fix(context)
2726 context.rounding = rounding
2728 return ans
2730 def is_canonical(self):
2731 """Return True if self is canonical; otherwise return False.
2733 Currently, the encoding of a Decimal instance is always
2734 canonical, so this method returns True for any Decimal.
2736 return True
2738 def is_finite(self):
2739 """Return True if self is finite; otherwise return False.
2741 A Decimal instance is considered finite if it is neither
2742 infinite nor a NaN.
2744 return not self._is_special
2746 def is_infinite(self):
2747 """Return True if self is infinite; otherwise return False."""
2748 return self._exp == 'F'
2750 def is_nan(self):
2751 """Return True if self is a qNaN or sNaN; otherwise return False."""
2752 return self._exp in ('n', 'N')
2754 def is_normal(self, context=None):
2755 """Return True if self is a normal number; otherwise return False."""
2756 if self._is_special or not self:
2757 return False
2758 if context is None:
2759 context = getcontext()
2760 return context.Emin <= self.adjusted() <= context.Emax
2762 def is_qnan(self):
2763 """Return True if self is a quiet NaN; otherwise return False."""
2764 return self._exp == 'n'
2766 def is_signed(self):
2767 """Return True if self is negative; otherwise return False."""
2768 return self._sign == 1
2770 def is_snan(self):
2771 """Return True if self is a signaling NaN; otherwise return False."""
2772 return self._exp == 'N'
2774 def is_subnormal(self, context=None):
2775 """Return True if self is subnormal; otherwise return False."""
2776 if self._is_special or not self:
2777 return False
2778 if context is None:
2779 context = getcontext()
2780 return self.adjusted() < context.Emin
2782 def is_zero(self):
2783 """Return True if self is a zero; otherwise return False."""
2784 return not self._is_special and self._int == '0'
2786 def _ln_exp_bound(self):
2787 """Compute a lower bound for the adjusted exponent of self.ln().
2788 In other words, compute r such that self.ln() >= 10**r. Assumes
2789 that self is finite and positive and that self != 1.
2792 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2793 adj = self._exp + len(self._int) - 1
2794 if adj >= 1:
2795 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2796 return len(str(adj*23//10)) - 1
2797 if adj <= -2:
2798 # argument <= 0.1
2799 return len(str((-1-adj)*23//10)) - 1
2800 op = _WorkRep(self)
2801 c, e = op.int, op.exp
2802 if adj == 0:
2803 # 1 < self < 10
2804 num = str(c-10**-e)
2805 den = str(c)
2806 return len(num) - len(den) - (num < den)
2807 # adj == -1, 0.1 <= self < 1
2808 return e + len(str(10**-e - c)) - 1
2811 def ln(self, context=None):
2812 """Returns the natural (base e) logarithm of self."""
2814 if context is None:
2815 context = getcontext()
2817 # ln(NaN) = NaN
2818 ans = self._check_nans(context=context)
2819 if ans:
2820 return ans
2822 # ln(0.0) == -Infinity
2823 if not self:
2824 return negInf
2826 # ln(Infinity) = Infinity
2827 if self._isinfinity() == 1:
2828 return Inf
2830 # ln(1.0) == 0.0
2831 if self == Dec_p1:
2832 return Dec_0
2834 # ln(negative) raises InvalidOperation
2835 if self._sign == 1:
2836 return context._raise_error(InvalidOperation,
2837 'ln of a negative value')
2839 # result is irrational, so necessarily inexact
2840 op = _WorkRep(self)
2841 c, e = op.int, op.exp
2842 p = context.prec
2844 # correctly rounded result: repeatedly increase precision by 3
2845 # until we get an unambiguously roundable result
2846 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2847 while True:
2848 coeff = _dlog(c, e, places)
2849 # assert len(str(abs(coeff)))-p >= 1
2850 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2851 break
2852 places += 3
2853 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2855 context = context._shallow_copy()
2856 rounding = context._set_rounding(ROUND_HALF_EVEN)
2857 ans = ans._fix(context)
2858 context.rounding = rounding
2859 return ans
2861 def _log10_exp_bound(self):
2862 """Compute a lower bound for the adjusted exponent of self.log10().
2863 In other words, find r such that self.log10() >= 10**r.
2864 Assumes that self is finite and positive and that self != 1.
2867 # For x >= 10 or x < 0.1 we only need a bound on the integer
2868 # part of log10(self), and this comes directly from the
2869 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2870 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2871 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2873 adj = self._exp + len(self._int) - 1
2874 if adj >= 1:
2875 # self >= 10
2876 return len(str(adj))-1
2877 if adj <= -2:
2878 # self < 0.1
2879 return len(str(-1-adj))-1
2880 op = _WorkRep(self)
2881 c, e = op.int, op.exp
2882 if adj == 0:
2883 # 1 < self < 10
2884 num = str(c-10**-e)
2885 den = str(231*c)
2886 return len(num) - len(den) - (num < den) + 2
2887 # adj == -1, 0.1 <= self < 1
2888 num = str(10**-e-c)
2889 return len(num) + e - (num < "231") - 1
2891 def log10(self, context=None):
2892 """Returns the base 10 logarithm of self."""
2894 if context is None:
2895 context = getcontext()
2897 # log10(NaN) = NaN
2898 ans = self._check_nans(context=context)
2899 if ans:
2900 return ans
2902 # log10(0.0) == -Infinity
2903 if not self:
2904 return negInf
2906 # log10(Infinity) = Infinity
2907 if self._isinfinity() == 1:
2908 return Inf
2910 # log10(negative or -Infinity) raises InvalidOperation
2911 if self._sign == 1:
2912 return context._raise_error(InvalidOperation,
2913 'log10 of a negative value')
2915 # log10(10**n) = n
2916 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
2917 # answer may need rounding
2918 ans = Decimal(self._exp + len(self._int) - 1)
2919 else:
2920 # result is irrational, so necessarily inexact
2921 op = _WorkRep(self)
2922 c, e = op.int, op.exp
2923 p = context.prec
2925 # correctly rounded result: repeatedly increase precision
2926 # until result is unambiguously roundable
2927 places = p-self._log10_exp_bound()+2
2928 while True:
2929 coeff = _dlog10(c, e, places)
2930 # assert len(str(abs(coeff)))-p >= 1
2931 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2932 break
2933 places += 3
2934 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2936 context = context._shallow_copy()
2937 rounding = context._set_rounding(ROUND_HALF_EVEN)
2938 ans = ans._fix(context)
2939 context.rounding = rounding
2940 return ans
2942 def logb(self, context=None):
2943 """ Returns the exponent of the magnitude of self's MSD.
2945 The result is the integer which is the exponent of the magnitude
2946 of the most significant digit of self (as though it were truncated
2947 to a single digit while maintaining the value of that digit and
2948 without limiting the resulting exponent).
2950 # logb(NaN) = NaN
2951 ans = self._check_nans(context=context)
2952 if ans:
2953 return ans
2955 if context is None:
2956 context = getcontext()
2958 # logb(+/-Inf) = +Inf
2959 if self._isinfinity():
2960 return Inf
2962 # logb(0) = -Inf, DivisionByZero
2963 if not self:
2964 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2966 # otherwise, simply return the adjusted exponent of self, as a
2967 # Decimal. Note that no attempt is made to fit the result
2968 # into the current context.
2969 return Decimal(self.adjusted())
2971 def _islogical(self):
2972 """Return True if self is a logical operand.
2974 For being logical, it must be a finite number with a sign of 0,
2975 an exponent of 0, and a coefficient whose digits must all be
2976 either 0 or 1.
2978 if self._sign != 0 or self._exp != 0:
2979 return False
2980 for dig in self._int:
2981 if dig not in '01':
2982 return False
2983 return True
2985 def _fill_logical(self, context, opa, opb):
2986 dif = context.prec - len(opa)
2987 if dif > 0:
2988 opa = '0'*dif + opa
2989 elif dif < 0:
2990 opa = opa[-context.prec:]
2991 dif = context.prec - len(opb)
2992 if dif > 0:
2993 opb = '0'*dif + opb
2994 elif dif < 0:
2995 opb = opb[-context.prec:]
2996 return opa, opb
2998 def logical_and(self, other, context=None):
2999 """Applies an 'and' operation between self and other's digits."""
3000 if context is None:
3001 context = getcontext()
3002 if not self._islogical() or not other._islogical():
3003 return context._raise_error(InvalidOperation)
3005 # fill to context.prec
3006 (opa, opb) = self._fill_logical(context, self._int, other._int)
3008 # make the operation, and clean starting zeroes
3009 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3010 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3012 def logical_invert(self, context=None):
3013 """Invert all its digits."""
3014 if context is None:
3015 context = getcontext()
3016 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3017 context)
3019 def logical_or(self, other, context=None):
3020 """Applies an 'or' operation between self and other's digits."""
3021 if context is None:
3022 context = getcontext()
3023 if not self._islogical() or not other._islogical():
3024 return context._raise_error(InvalidOperation)
3026 # fill to context.prec
3027 (opa, opb) = self._fill_logical(context, self._int, other._int)
3029 # make the operation, and clean starting zeroes
3030 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3031 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3033 def logical_xor(self, other, context=None):
3034 """Applies an 'xor' operation between self and other's digits."""
3035 if context is None:
3036 context = getcontext()
3037 if not self._islogical() or not other._islogical():
3038 return context._raise_error(InvalidOperation)
3040 # fill to context.prec
3041 (opa, opb) = self._fill_logical(context, self._int, other._int)
3043 # make the operation, and clean starting zeroes
3044 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3045 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3047 def max_mag(self, other, context=None):
3048 """Compares the values numerically with their sign ignored."""
3049 other = _convert_other(other, raiseit=True)
3051 if context is None:
3052 context = getcontext()
3054 if self._is_special or other._is_special:
3055 # If one operand is a quiet NaN and the other is number, then the
3056 # number is always returned
3057 sn = self._isnan()
3058 on = other._isnan()
3059 if sn or on:
3060 if on == 1 and sn != 2:
3061 return self._fix_nan(context)
3062 if sn == 1 and on != 2:
3063 return other._fix_nan(context)
3064 return self._check_nans(other, context)
3066 c = self.copy_abs().__cmp__(other.copy_abs())
3067 if c == 0:
3068 c = self.compare_total(other)
3070 if c == -1:
3071 ans = other
3072 else:
3073 ans = self
3075 return ans._fix(context)
3077 def min_mag(self, other, context=None):
3078 """Compares the values numerically with their sign ignored."""
3079 other = _convert_other(other, raiseit=True)
3081 if context is None:
3082 context = getcontext()
3084 if self._is_special or other._is_special:
3085 # If one operand is a quiet NaN and the other is number, then the
3086 # number is always returned
3087 sn = self._isnan()
3088 on = other._isnan()
3089 if sn or on:
3090 if on == 1 and sn != 2:
3091 return self._fix_nan(context)
3092 if sn == 1 and on != 2:
3093 return other._fix_nan(context)
3094 return self._check_nans(other, context)
3096 c = self.copy_abs().__cmp__(other.copy_abs())
3097 if c == 0:
3098 c = self.compare_total(other)
3100 if c == -1:
3101 ans = self
3102 else:
3103 ans = other
3105 return ans._fix(context)
3107 def next_minus(self, context=None):
3108 """Returns the largest representable number smaller than itself."""
3109 if context is None:
3110 context = getcontext()
3112 ans = self._check_nans(context=context)
3113 if ans:
3114 return ans
3116 if self._isinfinity() == -1:
3117 return negInf
3118 if self._isinfinity() == 1:
3119 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3121 context = context.copy()
3122 context._set_rounding(ROUND_FLOOR)
3123 context._ignore_all_flags()
3124 new_self = self._fix(context)
3125 if new_self != self:
3126 return new_self
3127 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3128 context)
3130 def next_plus(self, context=None):
3131 """Returns the smallest representable number larger than itself."""
3132 if context is None:
3133 context = getcontext()
3135 ans = self._check_nans(context=context)
3136 if ans:
3137 return ans
3139 if self._isinfinity() == 1:
3140 return Inf
3141 if self._isinfinity() == -1:
3142 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3144 context = context.copy()
3145 context._set_rounding(ROUND_CEILING)
3146 context._ignore_all_flags()
3147 new_self = self._fix(context)
3148 if new_self != self:
3149 return new_self
3150 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3151 context)
3153 def next_toward(self, other, context=None):
3154 """Returns the number closest to self, in the direction towards other.
3156 The result is the closest representable number to self
3157 (excluding self) that is in the direction towards other,
3158 unless both have the same value. If the two operands are
3159 numerically equal, then the result is a copy of self with the
3160 sign set to be the same as the sign of other.
3162 other = _convert_other(other, raiseit=True)
3164 if context is None:
3165 context = getcontext()
3167 ans = self._check_nans(other, context)
3168 if ans:
3169 return ans
3171 comparison = self.__cmp__(other)
3172 if comparison == 0:
3173 return self.copy_sign(other)
3175 if comparison == -1:
3176 ans = self.next_plus(context)
3177 else: # comparison == 1
3178 ans = self.next_minus(context)
3180 # decide which flags to raise using value of ans
3181 if ans._isinfinity():
3182 context._raise_error(Overflow,
3183 'Infinite result from next_toward',
3184 ans._sign)
3185 context._raise_error(Rounded)
3186 context._raise_error(Inexact)
3187 elif ans.adjusted() < context.Emin:
3188 context._raise_error(Underflow)
3189 context._raise_error(Subnormal)
3190 context._raise_error(Rounded)
3191 context._raise_error(Inexact)
3192 # if precision == 1 then we don't raise Clamped for a
3193 # result 0E-Etiny.
3194 if not ans:
3195 context._raise_error(Clamped)
3197 return ans
3199 def number_class(self, context=None):
3200 """Returns an indication of the class of self.
3202 The class is one of the following strings:
3203 sNaN
3205 -Infinity
3206 -Normal
3207 -Subnormal
3208 -Zero
3209 +Zero
3210 +Subnormal
3211 +Normal
3212 +Infinity
3214 if self.is_snan():
3215 return "sNaN"
3216 if self.is_qnan():
3217 return "NaN"
3218 inf = self._isinfinity()
3219 if inf == 1:
3220 return "+Infinity"
3221 if inf == -1:
3222 return "-Infinity"
3223 if self.is_zero():
3224 if self._sign:
3225 return "-Zero"
3226 else:
3227 return "+Zero"
3228 if context is None:
3229 context = getcontext()
3230 if self.is_subnormal(context=context):
3231 if self._sign:
3232 return "-Subnormal"
3233 else:
3234 return "+Subnormal"
3235 # just a normal, regular, boring number, :)
3236 if self._sign:
3237 return "-Normal"
3238 else:
3239 return "+Normal"
3241 def radix(self):
3242 """Just returns 10, as this is Decimal, :)"""
3243 return Decimal(10)
3245 def rotate(self, other, context=None):
3246 """Returns a rotated copy of self, value-of-other times."""
3247 if context is None:
3248 context = getcontext()
3250 ans = self._check_nans(other, context)
3251 if ans:
3252 return ans
3254 if other._exp != 0:
3255 return context._raise_error(InvalidOperation)
3256 if not (-context.prec <= int(other) <= context.prec):
3257 return context._raise_error(InvalidOperation)
3259 if self._isinfinity():
3260 return Decimal(self)
3262 # get values, pad if necessary
3263 torot = int(other)
3264 rotdig = self._int
3265 topad = context.prec - len(rotdig)
3266 if topad:
3267 rotdig = '0'*topad + rotdig
3269 # let's rotate!
3270 rotated = rotdig[torot:] + rotdig[:torot]
3271 return _dec_from_triple(self._sign,
3272 rotated.lstrip('0') or '0', self._exp)
3274 def scaleb (self, other, context=None):
3275 """Returns self operand after adding the second value to its exp."""
3276 if context is None:
3277 context = getcontext()
3279 ans = self._check_nans(other, context)
3280 if ans:
3281 return ans
3283 if other._exp != 0:
3284 return context._raise_error(InvalidOperation)
3285 liminf = -2 * (context.Emax + context.prec)
3286 limsup = 2 * (context.Emax + context.prec)
3287 if not (liminf <= int(other) <= limsup):
3288 return context._raise_error(InvalidOperation)
3290 if self._isinfinity():
3291 return Decimal(self)
3293 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3294 d = d._fix(context)
3295 return d
3297 def shift(self, other, context=None):
3298 """Returns a shifted copy of self, value-of-other times."""
3299 if context is None:
3300 context = getcontext()
3302 ans = self._check_nans(other, context)
3303 if ans:
3304 return ans
3306 if other._exp != 0:
3307 return context._raise_error(InvalidOperation)
3308 if not (-context.prec <= int(other) <= context.prec):
3309 return context._raise_error(InvalidOperation)
3311 if self._isinfinity():
3312 return Decimal(self)
3314 # get values, pad if necessary
3315 torot = int(other)
3316 if not torot:
3317 return Decimal(self)
3318 rotdig = self._int
3319 topad = context.prec - len(rotdig)
3320 if topad:
3321 rotdig = '0'*topad + rotdig
3323 # let's shift!
3324 if torot < 0:
3325 rotated = rotdig[:torot]
3326 else:
3327 rotated = rotdig + '0'*torot
3328 rotated = rotated[-context.prec:]
3330 return _dec_from_triple(self._sign,
3331 rotated.lstrip('0') or '0', self._exp)
3333 # Support for pickling, copy, and deepcopy
3334 def __reduce__(self):
3335 return (self.__class__, (str(self),))
3337 def __copy__(self):
3338 if type(self) == Decimal:
3339 return self # I'm immutable; therefore I am my own clone
3340 return self.__class__(str(self))
3342 def __deepcopy__(self, memo):
3343 if type(self) == Decimal:
3344 return self # My components are also immutable
3345 return self.__class__(str(self))
3347 def _dec_from_triple(sign, coefficient, exponent, special=False):
3348 """Create a decimal instance directly, without any validation,
3349 normalization (e.g. removal of leading zeros) or argument
3350 conversion.
3352 This function is for *internal use only*.
3355 self = object.__new__(Decimal)
3356 self._sign = sign
3357 self._int = coefficient
3358 self._exp = exponent
3359 self._is_special = special
3361 return self
3363 ##### Context class #######################################################
3366 # get rounding method function:
3367 rounding_functions = [name for name in Decimal.__dict__.keys()
3368 if name.startswith('_round_')]
3369 for name in rounding_functions:
3370 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3371 globalname = name[1:].upper()
3372 val = globals()[globalname]
3373 Decimal._pick_rounding_function[val] = name
3375 del name, val, globalname, rounding_functions
3377 class _ContextManager(object):
3378 """Context manager class to support localcontext().
3380 Sets a copy of the supplied context in __enter__() and restores
3381 the previous decimal context in __exit__()
3383 def __init__(self, new_context):
3384 self.new_context = new_context.copy()
3385 def __enter__(self):
3386 self.saved_context = getcontext()
3387 setcontext(self.new_context)
3388 return self.new_context
3389 def __exit__(self, t, v, tb):
3390 setcontext(self.saved_context)
3392 class Context(object):
3393 """Contains the context for a Decimal instance.
3395 Contains:
3396 prec - precision (for use in rounding, division, square roots..)
3397 rounding - rounding type (how you round)
3398 traps - If traps[exception] = 1, then the exception is
3399 raised when it is caused. Otherwise, a value is
3400 substituted in.
3401 flags - When an exception is caused, flags[exception] is incremented.
3402 (Whether or not the trap_enabler is set)
3403 Should be reset by user of Decimal instance.
3404 Emin - Minimum exponent
3405 Emax - Maximum exponent
3406 capitals - If 1, 1*10^1 is printed as 1E+1.
3407 If 0, printed as 1e1
3408 _clamp - If 1, change exponents if too high (Default 0)
3411 def __init__(self, prec=None, rounding=None,
3412 traps=None, flags=None,
3413 Emin=None, Emax=None,
3414 capitals=None, _clamp=0,
3415 _ignored_flags=None):
3416 if flags is None:
3417 flags = []
3418 if _ignored_flags is None:
3419 _ignored_flags = []
3420 if not isinstance(flags, dict):
3421 flags = dict([(s,s in flags) for s in _signals])
3422 del s
3423 if traps is not None and not isinstance(traps, dict):
3424 traps = dict([(s,s in traps) for s in _signals])
3425 del s
3426 for name, val in locals().items():
3427 if val is None:
3428 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3429 else:
3430 setattr(self, name, val)
3431 del self.self
3433 def __repr__(self):
3434 """Show the current context."""
3435 s = []
3436 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3437 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3438 % vars(self))
3439 names = [f.__name__ for f, v in self.flags.items() if v]
3440 s.append('flags=[' + ', '.join(names) + ']')
3441 names = [t.__name__ for t, v in self.traps.items() if v]
3442 s.append('traps=[' + ', '.join(names) + ']')
3443 return ', '.join(s) + ')'
3445 def clear_flags(self):
3446 """Reset all flags to zero"""
3447 for flag in self.flags:
3448 self.flags[flag] = 0
3450 def _shallow_copy(self):
3451 """Returns a shallow copy from self."""
3452 nc = Context(self.prec, self.rounding, self.traps,
3453 self.flags, self.Emin, self.Emax,
3454 self.capitals, self._clamp, self._ignored_flags)
3455 return nc
3457 def copy(self):
3458 """Returns a deep copy from self."""
3459 nc = Context(self.prec, self.rounding, self.traps.copy(),
3460 self.flags.copy(), self.Emin, self.Emax,
3461 self.capitals, self._clamp, self._ignored_flags)
3462 return nc
3463 __copy__ = copy
3465 def _raise_error(self, condition, explanation = None, *args):
3466 """Handles an error
3468 If the flag is in _ignored_flags, returns the default response.
3469 Otherwise, it increments the flag, then, if the corresponding
3470 trap_enabler is set, it reaises the exception. Otherwise, it returns
3471 the default value after incrementing the flag.
3473 error = _condition_map.get(condition, condition)
3474 if error in self._ignored_flags:
3475 # Don't touch the flag
3476 return error().handle(self, *args)
3478 self.flags[error] += 1
3479 if not self.traps[error]:
3480 # The errors define how to handle themselves.
3481 return condition().handle(self, *args)
3483 # Errors should only be risked on copies of the context
3484 # self._ignored_flags = []
3485 raise error, explanation
3487 def _ignore_all_flags(self):
3488 """Ignore all flags, if they are raised"""
3489 return self._ignore_flags(*_signals)
3491 def _ignore_flags(self, *flags):
3492 """Ignore the flags, if they are raised"""
3493 # Do not mutate-- This way, copies of a context leave the original
3494 # alone.
3495 self._ignored_flags = (self._ignored_flags + list(flags))
3496 return list(flags)
3498 def _regard_flags(self, *flags):
3499 """Stop ignoring the flags, if they are raised"""
3500 if flags and isinstance(flags[0], (tuple,list)):
3501 flags = flags[0]
3502 for flag in flags:
3503 self._ignored_flags.remove(flag)
3505 def __hash__(self):
3506 """A Context cannot be hashed."""
3507 # We inherit object.__hash__, so we must deny this explicitly
3508 raise TypeError("Cannot hash a Context.")
3510 def Etiny(self):
3511 """Returns Etiny (= Emin - prec + 1)"""
3512 return int(self.Emin - self.prec + 1)
3514 def Etop(self):
3515 """Returns maximum exponent (= Emax - prec + 1)"""
3516 return int(self.Emax - self.prec + 1)
3518 def _set_rounding(self, type):
3519 """Sets the rounding type.
3521 Sets the rounding type, and returns the current (previous)
3522 rounding type. Often used like:
3524 context = context.copy()
3525 # so you don't change the calling context
3526 # if an error occurs in the middle.
3527 rounding = context._set_rounding(ROUND_UP)
3528 val = self.__sub__(other, context=context)
3529 context._set_rounding(rounding)
3531 This will make it round up for that operation.
3533 rounding = self.rounding
3534 self.rounding= type
3535 return rounding
3537 def create_decimal(self, num='0'):
3538 """Creates a new Decimal instance but using self as context.
3540 This method implements the to-number operation of the
3541 IBM Decimal specification."""
3543 if isinstance(num, basestring) and num != num.strip():
3544 return self._raise_error(ConversionSyntax,
3545 "no trailing or leading whitespace is "
3546 "permitted.")
3548 d = Decimal(num, context=self)
3549 if d._isnan() and len(d._int) > self.prec - self._clamp:
3550 return self._raise_error(ConversionSyntax,
3551 "diagnostic info too long in NaN")
3552 return d._fix(self)
3554 # Methods
3555 def abs(self, a):
3556 """Returns the absolute value of the operand.
3558 If the operand is negative, the result is the same as using the minus
3559 operation on the operand. Otherwise, the result is the same as using
3560 the plus operation on the operand.
3562 >>> ExtendedContext.abs(Decimal('2.1'))
3563 Decimal("2.1")
3564 >>> ExtendedContext.abs(Decimal('-100'))
3565 Decimal("100")
3566 >>> ExtendedContext.abs(Decimal('101.5'))
3567 Decimal("101.5")
3568 >>> ExtendedContext.abs(Decimal('-101.5'))
3569 Decimal("101.5")
3571 return a.__abs__(context=self)
3573 def add(self, a, b):
3574 """Return the sum of the two operands.
3576 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3577 Decimal("19.00")
3578 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3579 Decimal("1.02E+4")
3581 return a.__add__(b, context=self)
3583 def _apply(self, a):
3584 return str(a._fix(self))
3586 def canonical(self, a):
3587 """Returns the same Decimal object.
3589 As we do not have different encodings for the same number, the
3590 received object already is in its canonical form.
3592 >>> ExtendedContext.canonical(Decimal('2.50'))
3593 Decimal("2.50")
3595 return a.canonical(context=self)
3597 def compare(self, a, b):
3598 """Compares values numerically.
3600 If the signs of the operands differ, a value representing each operand
3601 ('-1' if the operand is less than zero, '0' if the operand is zero or
3602 negative zero, or '1' if the operand is greater than zero) is used in
3603 place of that operand for the comparison instead of the actual
3604 operand.
3606 The comparison is then effected by subtracting the second operand from
3607 the first and then returning a value according to the result of the
3608 subtraction: '-1' if the result is less than zero, '0' if the result is
3609 zero or negative zero, or '1' if the result is greater than zero.
3611 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3612 Decimal("-1")
3613 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3614 Decimal("0")
3615 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3616 Decimal("0")
3617 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3618 Decimal("1")
3619 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3620 Decimal("1")
3621 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3622 Decimal("-1")
3624 return a.compare(b, context=self)
3626 def compare_signal(self, a, b):
3627 """Compares the values of the two operands numerically.
3629 It's pretty much like compare(), but all NaNs signal, with signaling
3630 NaNs taking precedence over quiet NaNs.
3632 >>> c = ExtendedContext
3633 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3634 Decimal("-1")
3635 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3636 Decimal("0")
3637 >>> c.flags[InvalidOperation] = 0
3638 >>> print c.flags[InvalidOperation]
3640 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3641 Decimal("NaN")
3642 >>> print c.flags[InvalidOperation]
3644 >>> c.flags[InvalidOperation] = 0
3645 >>> print c.flags[InvalidOperation]
3647 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3648 Decimal("NaN")
3649 >>> print c.flags[InvalidOperation]
3652 return a.compare_signal(b, context=self)
3654 def compare_total(self, a, b):
3655 """Compares two operands using their abstract representation.
3657 This is not like the standard compare, which use their numerical
3658 value. Note that a total ordering is defined for all possible abstract
3659 representations.
3661 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3662 Decimal("-1")
3663 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3664 Decimal("-1")
3665 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3666 Decimal("-1")
3667 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3668 Decimal("0")
3669 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3670 Decimal("1")
3671 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3672 Decimal("-1")
3674 return a.compare_total(b)
3676 def compare_total_mag(self, a, b):
3677 """Compares two operands using their abstract representation ignoring sign.
3679 Like compare_total, but with operand's sign ignored and assumed to be 0.
3681 return a.compare_total_mag(b)
3683 def copy_abs(self, a):
3684 """Returns a copy of the operand with the sign set to 0.
3686 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3687 Decimal("2.1")
3688 >>> ExtendedContext.copy_abs(Decimal('-100'))
3689 Decimal("100")
3691 return a.copy_abs()
3693 def copy_decimal(self, a):
3694 """Returns a copy of the decimal objet.
3696 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3697 Decimal("2.1")
3698 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3699 Decimal("-1.00")
3701 return Decimal(a)
3703 def copy_negate(self, a):
3704 """Returns a copy of the operand with the sign inverted.
3706 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3707 Decimal("-101.5")
3708 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3709 Decimal("101.5")
3711 return a.copy_negate()
3713 def copy_sign(self, a, b):
3714 """Copies the second operand's sign to the first one.
3716 In detail, it returns a copy of the first operand with the sign
3717 equal to the sign of the second operand.
3719 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3720 Decimal("1.50")
3721 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3722 Decimal("1.50")
3723 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3724 Decimal("-1.50")
3725 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3726 Decimal("-1.50")
3728 return a.copy_sign(b)
3730 def divide(self, a, b):
3731 """Decimal division in a specified context.
3733 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3734 Decimal("0.333333333")
3735 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3736 Decimal("0.666666667")
3737 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3738 Decimal("2.5")
3739 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3740 Decimal("0.1")
3741 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3742 Decimal("1")
3743 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3744 Decimal("4.00")
3745 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3746 Decimal("1.20")
3747 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3748 Decimal("10")
3749 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3750 Decimal("1000")
3751 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3752 Decimal("1.20E+6")
3754 return a.__div__(b, context=self)
3756 def divide_int(self, a, b):
3757 """Divides two numbers and returns the integer part of the result.
3759 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3760 Decimal("0")
3761 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3762 Decimal("3")
3763 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3764 Decimal("3")
3766 return a.__floordiv__(b, context=self)
3768 def divmod(self, a, b):
3769 return a.__divmod__(b, context=self)
3771 def exp(self, a):
3772 """Returns e ** a.
3774 >>> c = ExtendedContext.copy()
3775 >>> c.Emin = -999
3776 >>> c.Emax = 999
3777 >>> c.exp(Decimal('-Infinity'))
3778 Decimal("0")
3779 >>> c.exp(Decimal('-1'))
3780 Decimal("0.367879441")
3781 >>> c.exp(Decimal('0'))
3782 Decimal("1")
3783 >>> c.exp(Decimal('1'))
3784 Decimal("2.71828183")
3785 >>> c.exp(Decimal('0.693147181'))
3786 Decimal("2.00000000")
3787 >>> c.exp(Decimal('+Infinity'))
3788 Decimal("Infinity")
3790 return a.exp(context=self)
3792 def fma(self, a, b, c):
3793 """Returns a multiplied by b, plus c.
3795 The first two operands are multiplied together, using multiply,
3796 the third operand is then added to the result of that
3797 multiplication, using add, all with only one final rounding.
3799 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3800 Decimal("22")
3801 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3802 Decimal("-8")
3803 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3804 Decimal("1.38435736E+12")
3806 return a.fma(b, c, context=self)
3808 def is_canonical(self, a):
3809 """Return True if the operand is canonical; otherwise return False.
3811 Currently, the encoding of a Decimal instance is always
3812 canonical, so this method returns True for any Decimal.
3814 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3815 True
3817 return a.is_canonical()
3819 def is_finite(self, a):
3820 """Return True if the operand is finite; otherwise return False.
3822 A Decimal instance is considered finite if it is neither
3823 infinite nor a NaN.
3825 >>> ExtendedContext.is_finite(Decimal('2.50'))
3826 True
3827 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3828 True
3829 >>> ExtendedContext.is_finite(Decimal('0'))
3830 True
3831 >>> ExtendedContext.is_finite(Decimal('Inf'))
3832 False
3833 >>> ExtendedContext.is_finite(Decimal('NaN'))
3834 False
3836 return a.is_finite()
3838 def is_infinite(self, a):
3839 """Return True if the operand is infinite; otherwise return False.
3841 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3842 False
3843 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3844 True
3845 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3846 False
3848 return a.is_infinite()
3850 def is_nan(self, a):
3851 """Return True if the operand is a qNaN or sNaN;
3852 otherwise return False.
3854 >>> ExtendedContext.is_nan(Decimal('2.50'))
3855 False
3856 >>> ExtendedContext.is_nan(Decimal('NaN'))
3857 True
3858 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3859 True
3861 return a.is_nan()
3863 def is_normal(self, a):
3864 """Return True if the operand is a normal number;
3865 otherwise return False.
3867 >>> c = ExtendedContext.copy()
3868 >>> c.Emin = -999
3869 >>> c.Emax = 999
3870 >>> c.is_normal(Decimal('2.50'))
3871 True
3872 >>> c.is_normal(Decimal('0.1E-999'))
3873 False
3874 >>> c.is_normal(Decimal('0.00'))
3875 False
3876 >>> c.is_normal(Decimal('-Inf'))
3877 False
3878 >>> c.is_normal(Decimal('NaN'))
3879 False
3881 return a.is_normal(context=self)
3883 def is_qnan(self, a):
3884 """Return True if the operand is a quiet NaN; otherwise return False.
3886 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3887 False
3888 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3889 True
3890 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3891 False
3893 return a.is_qnan()
3895 def is_signed(self, a):
3896 """Return True if the operand is negative; otherwise return False.
3898 >>> ExtendedContext.is_signed(Decimal('2.50'))
3899 False
3900 >>> ExtendedContext.is_signed(Decimal('-12'))
3901 True
3902 >>> ExtendedContext.is_signed(Decimal('-0'))
3903 True
3905 return a.is_signed()
3907 def is_snan(self, a):
3908 """Return True if the operand is a signaling NaN;
3909 otherwise return False.
3911 >>> ExtendedContext.is_snan(Decimal('2.50'))
3912 False
3913 >>> ExtendedContext.is_snan(Decimal('NaN'))
3914 False
3915 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3916 True
3918 return a.is_snan()
3920 def is_subnormal(self, a):
3921 """Return True if the operand is subnormal; otherwise return False.
3923 >>> c = ExtendedContext.copy()
3924 >>> c.Emin = -999
3925 >>> c.Emax = 999
3926 >>> c.is_subnormal(Decimal('2.50'))
3927 False
3928 >>> c.is_subnormal(Decimal('0.1E-999'))
3929 True
3930 >>> c.is_subnormal(Decimal('0.00'))
3931 False
3932 >>> c.is_subnormal(Decimal('-Inf'))
3933 False
3934 >>> c.is_subnormal(Decimal('NaN'))
3935 False
3937 return a.is_subnormal(context=self)
3939 def is_zero(self, a):
3940 """Return True if the operand is a zero; otherwise return False.
3942 >>> ExtendedContext.is_zero(Decimal('0'))
3943 True
3944 >>> ExtendedContext.is_zero(Decimal('2.50'))
3945 False
3946 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3947 True
3949 return a.is_zero()
3951 def ln(self, a):
3952 """Returns the natural (base e) logarithm of the operand.
3954 >>> c = ExtendedContext.copy()
3955 >>> c.Emin = -999
3956 >>> c.Emax = 999
3957 >>> c.ln(Decimal('0'))
3958 Decimal("-Infinity")
3959 >>> c.ln(Decimal('1.000'))
3960 Decimal("0")
3961 >>> c.ln(Decimal('2.71828183'))
3962 Decimal("1.00000000")
3963 >>> c.ln(Decimal('10'))
3964 Decimal("2.30258509")
3965 >>> c.ln(Decimal('+Infinity'))
3966 Decimal("Infinity")
3968 return a.ln(context=self)
3970 def log10(self, a):
3971 """Returns the base 10 logarithm of the operand.
3973 >>> c = ExtendedContext.copy()
3974 >>> c.Emin = -999
3975 >>> c.Emax = 999
3976 >>> c.log10(Decimal('0'))
3977 Decimal("-Infinity")
3978 >>> c.log10(Decimal('0.001'))
3979 Decimal("-3")
3980 >>> c.log10(Decimal('1.000'))
3981 Decimal("0")
3982 >>> c.log10(Decimal('2'))
3983 Decimal("0.301029996")
3984 >>> c.log10(Decimal('10'))
3985 Decimal("1")
3986 >>> c.log10(Decimal('70'))
3987 Decimal("1.84509804")
3988 >>> c.log10(Decimal('+Infinity'))
3989 Decimal("Infinity")
3991 return a.log10(context=self)
3993 def logb(self, a):
3994 """ Returns the exponent of the magnitude of the operand's MSD.
3996 The result is the integer which is the exponent of the magnitude
3997 of the most significant digit of the operand (as though the
3998 operand were truncated to a single digit while maintaining the
3999 value of that digit and without limiting the resulting exponent).
4001 >>> ExtendedContext.logb(Decimal('250'))
4002 Decimal("2")
4003 >>> ExtendedContext.logb(Decimal('2.50'))
4004 Decimal("0")
4005 >>> ExtendedContext.logb(Decimal('0.03'))
4006 Decimal("-2")
4007 >>> ExtendedContext.logb(Decimal('0'))
4008 Decimal("-Infinity")
4010 return a.logb(context=self)
4012 def logical_and(self, a, b):
4013 """Applies the logical operation 'and' between each operand's digits.
4015 The operands must be both logical numbers.
4017 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4018 Decimal("0")
4019 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4020 Decimal("0")
4021 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4022 Decimal("0")
4023 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4024 Decimal("1")
4025 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4026 Decimal("1000")
4027 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4028 Decimal("10")
4030 return a.logical_and(b, context=self)
4032 def logical_invert(self, a):
4033 """Invert all the digits in the operand.
4035 The operand must be a logical number.
4037 >>> ExtendedContext.logical_invert(Decimal('0'))
4038 Decimal("111111111")
4039 >>> ExtendedContext.logical_invert(Decimal('1'))
4040 Decimal("111111110")
4041 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4042 Decimal("0")
4043 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4044 Decimal("10101010")
4046 return a.logical_invert(context=self)
4048 def logical_or(self, a, b):
4049 """Applies the logical operation 'or' between each operand's digits.
4051 The operands must be both logical numbers.
4053 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4054 Decimal("0")
4055 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4056 Decimal("1")
4057 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4058 Decimal("1")
4059 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4060 Decimal("1")
4061 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4062 Decimal("1110")
4063 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4064 Decimal("1110")
4066 return a.logical_or(b, context=self)
4068 def logical_xor(self, a, b):
4069 """Applies the logical operation 'xor' between each operand's digits.
4071 The operands must be both logical numbers.
4073 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4074 Decimal("0")
4075 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4076 Decimal("1")
4077 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4078 Decimal("1")
4079 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4080 Decimal("0")
4081 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4082 Decimal("110")
4083 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4084 Decimal("1101")
4086 return a.logical_xor(b, context=self)
4088 def max(self, a,b):
4089 """max compares two values numerically and returns the maximum.
4091 If either operand is a NaN then the general rules apply.
4092 Otherwise, the operands are compared as though by the compare
4093 operation. If they are numerically equal then the left-hand operand
4094 is chosen as the result. Otherwise the maximum (closer to positive
4095 infinity) of the two operands is chosen as the result.
4097 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4098 Decimal("3")
4099 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4100 Decimal("3")
4101 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4102 Decimal("1")
4103 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4104 Decimal("7")
4106 return a.max(b, context=self)
4108 def max_mag(self, a, b):
4109 """Compares the values numerically with their sign ignored."""
4110 return a.max_mag(b, context=self)
4112 def min(self, a,b):
4113 """min compares two values numerically and returns the minimum.
4115 If either operand is a NaN then the general rules apply.
4116 Otherwise, the operands are compared as though by the compare
4117 operation. If they are numerically equal then the left-hand operand
4118 is chosen as the result. Otherwise the minimum (closer to negative
4119 infinity) of the two operands is chosen as the result.
4121 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4122 Decimal("2")
4123 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4124 Decimal("-10")
4125 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4126 Decimal("1.0")
4127 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4128 Decimal("7")
4130 return a.min(b, context=self)
4132 def min_mag(self, a, b):
4133 """Compares the values numerically with their sign ignored."""
4134 return a.min_mag(b, context=self)
4136 def minus(self, a):
4137 """Minus corresponds to unary prefix minus in Python.
4139 The operation is evaluated using the same rules as subtract; the
4140 operation minus(a) is calculated as subtract('0', a) where the '0'
4141 has the same exponent as the operand.
4143 >>> ExtendedContext.minus(Decimal('1.3'))
4144 Decimal("-1.3")
4145 >>> ExtendedContext.minus(Decimal('-1.3'))
4146 Decimal("1.3")
4148 return a.__neg__(context=self)
4150 def multiply(self, a, b):
4151 """multiply multiplies two operands.
4153 If either operand is a special value then the general rules apply.
4154 Otherwise, the operands are multiplied together ('long multiplication'),
4155 resulting in a number which may be as long as the sum of the lengths
4156 of the two operands.
4158 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4159 Decimal("3.60")
4160 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4161 Decimal("21")
4162 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4163 Decimal("0.72")
4164 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4165 Decimal("-0.0")
4166 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4167 Decimal("4.28135971E+11")
4169 return a.__mul__(b, context=self)
4171 def next_minus(self, a):
4172 """Returns the largest representable number smaller than a.
4174 >>> c = ExtendedContext.copy()
4175 >>> c.Emin = -999
4176 >>> c.Emax = 999
4177 >>> ExtendedContext.next_minus(Decimal('1'))
4178 Decimal("0.999999999")
4179 >>> c.next_minus(Decimal('1E-1007'))
4180 Decimal("0E-1007")
4181 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4182 Decimal("-1.00000004")
4183 >>> c.next_minus(Decimal('Infinity'))
4184 Decimal("9.99999999E+999")
4186 return a.next_minus(context=self)
4188 def next_plus(self, a):
4189 """Returns the smallest representable number larger than a.
4191 >>> c = ExtendedContext.copy()
4192 >>> c.Emin = -999
4193 >>> c.Emax = 999
4194 >>> ExtendedContext.next_plus(Decimal('1'))
4195 Decimal("1.00000001")
4196 >>> c.next_plus(Decimal('-1E-1007'))
4197 Decimal("-0E-1007")
4198 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4199 Decimal("-1.00000002")
4200 >>> c.next_plus(Decimal('-Infinity'))
4201 Decimal("-9.99999999E+999")
4203 return a.next_plus(context=self)
4205 def next_toward(self, a, b):
4206 """Returns the number closest to a, in direction towards b.
4208 The result is the closest representable number from the first
4209 operand (but not the first operand) that is in the direction
4210 towards the second operand, unless the operands have the same
4211 value.
4213 >>> c = ExtendedContext.copy()
4214 >>> c.Emin = -999
4215 >>> c.Emax = 999
4216 >>> c.next_toward(Decimal('1'), Decimal('2'))
4217 Decimal("1.00000001")
4218 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4219 Decimal("-0E-1007")
4220 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4221 Decimal("-1.00000002")
4222 >>> c.next_toward(Decimal('1'), Decimal('0'))
4223 Decimal("0.999999999")
4224 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4225 Decimal("0E-1007")
4226 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4227 Decimal("-1.00000004")
4228 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4229 Decimal("-0.00")
4231 return a.next_toward(b, context=self)
4233 def normalize(self, a):
4234 """normalize reduces an operand to its simplest form.
4236 Essentially a plus operation with all trailing zeros removed from the
4237 result.
4239 >>> ExtendedContext.normalize(Decimal('2.1'))
4240 Decimal("2.1")
4241 >>> ExtendedContext.normalize(Decimal('-2.0'))
4242 Decimal("-2")
4243 >>> ExtendedContext.normalize(Decimal('1.200'))
4244 Decimal("1.2")
4245 >>> ExtendedContext.normalize(Decimal('-120'))
4246 Decimal("-1.2E+2")
4247 >>> ExtendedContext.normalize(Decimal('120.00'))
4248 Decimal("1.2E+2")
4249 >>> ExtendedContext.normalize(Decimal('0.00'))
4250 Decimal("0")
4252 return a.normalize(context=self)
4254 def number_class(self, a):
4255 """Returns an indication of the class of the operand.
4257 The class is one of the following strings:
4258 -sNaN
4259 -NaN
4260 -Infinity
4261 -Normal
4262 -Subnormal
4263 -Zero
4264 +Zero
4265 +Subnormal
4266 +Normal
4267 +Infinity
4269 >>> c = Context(ExtendedContext)
4270 >>> c.Emin = -999
4271 >>> c.Emax = 999
4272 >>> c.number_class(Decimal('Infinity'))
4273 '+Infinity'
4274 >>> c.number_class(Decimal('1E-10'))
4275 '+Normal'
4276 >>> c.number_class(Decimal('2.50'))
4277 '+Normal'
4278 >>> c.number_class(Decimal('0.1E-999'))
4279 '+Subnormal'
4280 >>> c.number_class(Decimal('0'))
4281 '+Zero'
4282 >>> c.number_class(Decimal('-0'))
4283 '-Zero'
4284 >>> c.number_class(Decimal('-0.1E-999'))
4285 '-Subnormal'
4286 >>> c.number_class(Decimal('-1E-10'))
4287 '-Normal'
4288 >>> c.number_class(Decimal('-2.50'))
4289 '-Normal'
4290 >>> c.number_class(Decimal('-Infinity'))
4291 '-Infinity'
4292 >>> c.number_class(Decimal('NaN'))
4293 'NaN'
4294 >>> c.number_class(Decimal('-NaN'))
4295 'NaN'
4296 >>> c.number_class(Decimal('sNaN'))
4297 'sNaN'
4299 return a.number_class(context=self)
4301 def plus(self, a):
4302 """Plus corresponds to unary prefix plus in Python.
4304 The operation is evaluated using the same rules as add; the
4305 operation plus(a) is calculated as add('0', a) where the '0'
4306 has the same exponent as the operand.
4308 >>> ExtendedContext.plus(Decimal('1.3'))
4309 Decimal("1.3")
4310 >>> ExtendedContext.plus(Decimal('-1.3'))
4311 Decimal("-1.3")
4313 return a.__pos__(context=self)
4315 def power(self, a, b, modulo=None):
4316 """Raises a to the power of b, to modulo if given.
4318 With two arguments, compute a**b. If a is negative then b
4319 must be integral. The result will be inexact unless b is
4320 integral and the result is finite and can be expressed exactly
4321 in 'precision' digits.
4323 With three arguments, compute (a**b) % modulo. For the
4324 three argument form, the following restrictions on the
4325 arguments hold:
4327 - all three arguments must be integral
4328 - b must be nonnegative
4329 - at least one of a or b must be nonzero
4330 - modulo must be nonzero and have at most 'precision' digits
4332 The result of pow(a, b, modulo) is identical to the result
4333 that would be obtained by computing (a**b) % modulo with
4334 unbounded precision, but is computed more efficiently. It is
4335 always exact.
4337 >>> c = ExtendedContext.copy()
4338 >>> c.Emin = -999
4339 >>> c.Emax = 999
4340 >>> c.power(Decimal('2'), Decimal('3'))
4341 Decimal("8")
4342 >>> c.power(Decimal('-2'), Decimal('3'))
4343 Decimal("-8")
4344 >>> c.power(Decimal('2'), Decimal('-3'))
4345 Decimal("0.125")
4346 >>> c.power(Decimal('1.7'), Decimal('8'))
4347 Decimal("69.7575744")
4348 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4349 Decimal("2.00000000")
4350 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4351 Decimal("0")
4352 >>> c.power(Decimal('Infinity'), Decimal('0'))
4353 Decimal("1")
4354 >>> c.power(Decimal('Infinity'), Decimal('1'))
4355 Decimal("Infinity")
4356 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4357 Decimal("-0")
4358 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4359 Decimal("1")
4360 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4361 Decimal("-Infinity")
4362 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4363 Decimal("Infinity")
4364 >>> c.power(Decimal('0'), Decimal('0'))
4365 Decimal("NaN")
4367 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4368 Decimal("11")
4369 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4370 Decimal("-11")
4371 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4372 Decimal("1")
4373 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4374 Decimal("11")
4375 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4376 Decimal("11729830")
4377 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4378 Decimal("-0")
4379 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4380 Decimal("1")
4382 return a.__pow__(b, modulo, context=self)
4384 def quantize(self, a, b):
4385 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4387 The coefficient of the result is derived from that of the left-hand
4388 operand. It may be rounded using the current rounding setting (if the
4389 exponent is being increased), multiplied by a positive power of ten (if
4390 the exponent is being decreased), or is unchanged (if the exponent is
4391 already equal to that of the right-hand operand).
4393 Unlike other operations, if the length of the coefficient after the
4394 quantize operation would be greater than precision then an Invalid
4395 operation condition is raised. This guarantees that, unless there is
4396 an error condition, the exponent of the result of a quantize is always
4397 equal to that of the right-hand operand.
4399 Also unlike other operations, quantize will never raise Underflow, even
4400 if the result is subnormal and inexact.
4402 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4403 Decimal("2.170")
4404 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4405 Decimal("2.17")
4406 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4407 Decimal("2.2")
4408 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4409 Decimal("2")
4410 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4411 Decimal("0E+1")
4412 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4413 Decimal("-Infinity")
4414 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4415 Decimal("NaN")
4416 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4417 Decimal("-0")
4418 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4419 Decimal("-0E+5")
4420 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4421 Decimal("NaN")
4422 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4423 Decimal("NaN")
4424 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4425 Decimal("217.0")
4426 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4427 Decimal("217")
4428 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4429 Decimal("2.2E+2")
4430 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4431 Decimal("2E+2")
4433 return a.quantize(b, context=self)
4435 def radix(self):
4436 """Just returns 10, as this is Decimal, :)
4438 >>> ExtendedContext.radix()
4439 Decimal("10")
4441 return Decimal(10)
4443 def remainder(self, a, b):
4444 """Returns the remainder from integer division.
4446 The result is the residue of the dividend after the operation of
4447 calculating integer division as described for divide-integer, rounded
4448 to precision digits if necessary. The sign of the result, if
4449 non-zero, is the same as that of the original dividend.
4451 This operation will fail under the same conditions as integer division
4452 (that is, if integer division on the same two operands would fail, the
4453 remainder cannot be calculated).
4455 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4456 Decimal("2.1")
4457 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4458 Decimal("1")
4459 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4460 Decimal("-1")
4461 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4462 Decimal("0.2")
4463 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4464 Decimal("0.1")
4465 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4466 Decimal("1.0")
4468 return a.__mod__(b, context=self)
4470 def remainder_near(self, a, b):
4471 """Returns to be "a - b * n", where n is the integer nearest the exact
4472 value of "x / b" (if two integers are equally near then the even one
4473 is chosen). If the result is equal to 0 then its sign will be the
4474 sign of a.
4476 This operation will fail under the same conditions as integer division
4477 (that is, if integer division on the same two operands would fail, the
4478 remainder cannot be calculated).
4480 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4481 Decimal("-0.9")
4482 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4483 Decimal("-2")
4484 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4485 Decimal("1")
4486 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4487 Decimal("-1")
4488 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4489 Decimal("0.2")
4490 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4491 Decimal("0.1")
4492 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4493 Decimal("-0.3")
4495 return a.remainder_near(b, context=self)
4497 def rotate(self, a, b):
4498 """Returns a rotated copy of a, b times.
4500 The coefficient of the result is a rotated copy of the digits in
4501 the coefficient of the first operand. The number of places of
4502 rotation is taken from the absolute value of the second operand,
4503 with the rotation being to the left if the second operand is
4504 positive or to the right otherwise.
4506 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4507 Decimal("400000003")
4508 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4509 Decimal("12")
4510 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4511 Decimal("891234567")
4512 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4513 Decimal("123456789")
4514 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4515 Decimal("345678912")
4517 return a.rotate(b, context=self)
4519 def same_quantum(self, a, b):
4520 """Returns True if the two operands have the same exponent.
4522 The result is never affected by either the sign or the coefficient of
4523 either operand.
4525 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4526 False
4527 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4528 True
4529 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4530 False
4531 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4532 True
4534 return a.same_quantum(b)
4536 def scaleb (self, a, b):
4537 """Returns the first operand after adding the second value its exp.
4539 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4540 Decimal("0.0750")
4541 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4542 Decimal("7.50")
4543 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4544 Decimal("7.50E+3")
4546 return a.scaleb (b, context=self)
4548 def shift(self, a, b):
4549 """Returns a shifted copy of a, b times.
4551 The coefficient of the result is a shifted copy of the digits
4552 in the coefficient of the first operand. The number of places
4553 to shift is taken from the absolute value of the second operand,
4554 with the shift being to the left if the second operand is
4555 positive or to the right otherwise. Digits shifted into the
4556 coefficient are zeros.
4558 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4559 Decimal("400000000")
4560 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4561 Decimal("0")
4562 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4563 Decimal("1234567")
4564 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4565 Decimal("123456789")
4566 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4567 Decimal("345678900")
4569 return a.shift(b, context=self)
4571 def sqrt(self, a):
4572 """Square root of a non-negative number to context precision.
4574 If the result must be inexact, it is rounded using the round-half-even
4575 algorithm.
4577 >>> ExtendedContext.sqrt(Decimal('0'))
4578 Decimal("0")
4579 >>> ExtendedContext.sqrt(Decimal('-0'))
4580 Decimal("-0")
4581 >>> ExtendedContext.sqrt(Decimal('0.39'))
4582 Decimal("0.624499800")
4583 >>> ExtendedContext.sqrt(Decimal('100'))
4584 Decimal("10")
4585 >>> ExtendedContext.sqrt(Decimal('1'))
4586 Decimal("1")
4587 >>> ExtendedContext.sqrt(Decimal('1.0'))
4588 Decimal("1.0")
4589 >>> ExtendedContext.sqrt(Decimal('1.00'))
4590 Decimal("1.0")
4591 >>> ExtendedContext.sqrt(Decimal('7'))
4592 Decimal("2.64575131")
4593 >>> ExtendedContext.sqrt(Decimal('10'))
4594 Decimal("3.16227766")
4595 >>> ExtendedContext.prec
4598 return a.sqrt(context=self)
4600 def subtract(self, a, b):
4601 """Return the difference between the two operands.
4603 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4604 Decimal("0.23")
4605 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4606 Decimal("0.00")
4607 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4608 Decimal("-0.77")
4610 return a.__sub__(b, context=self)
4612 def to_eng_string(self, a):
4613 """Converts a number to a string, using scientific notation.
4615 The operation is not affected by the context.
4617 return a.to_eng_string(context=self)
4619 def to_sci_string(self, a):
4620 """Converts a number to a string, using scientific notation.
4622 The operation is not affected by the context.
4624 return a.__str__(context=self)
4626 def to_integral_exact(self, a):
4627 """Rounds to an integer.
4629 When the operand has a negative exponent, the result is the same
4630 as using the quantize() operation using the given operand as the
4631 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4632 of the operand as the precision setting; Inexact and Rounded flags
4633 are allowed in this operation. The rounding mode is taken from the
4634 context.
4636 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4637 Decimal("2")
4638 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4639 Decimal("100")
4640 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4641 Decimal("100")
4642 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4643 Decimal("102")
4644 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4645 Decimal("-102")
4646 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4647 Decimal("1.0E+6")
4648 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4649 Decimal("7.89E+77")
4650 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4651 Decimal("-Infinity")
4653 return a.to_integral_exact(context=self)
4655 def to_integral_value(self, a):
4656 """Rounds to an integer.
4658 When the operand has a negative exponent, the result is the same
4659 as using the quantize() operation using the given operand as the
4660 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4661 of the operand as the precision setting, except that no flags will
4662 be set. The rounding mode is taken from the context.
4664 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4665 Decimal("2")
4666 >>> ExtendedContext.to_integral_value(Decimal('100'))
4667 Decimal("100")
4668 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4669 Decimal("100")
4670 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4671 Decimal("102")
4672 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4673 Decimal("-102")
4674 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4675 Decimal("1.0E+6")
4676 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4677 Decimal("7.89E+77")
4678 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4679 Decimal("-Infinity")
4681 return a.to_integral_value(context=self)
4683 # the method name changed, but we provide also the old one, for compatibility
4684 to_integral = to_integral_value
4686 class _WorkRep(object):
4687 __slots__ = ('sign','int','exp')
4688 # sign: 0 or 1
4689 # int: int or long
4690 # exp: None, int, or string
4692 def __init__(self, value=None):
4693 if value is None:
4694 self.sign = None
4695 self.int = 0
4696 self.exp = None
4697 elif isinstance(value, Decimal):
4698 self.sign = value._sign
4699 self.int = int(value._int)
4700 self.exp = value._exp
4701 else:
4702 # assert isinstance(value, tuple)
4703 self.sign = value[0]
4704 self.int = value[1]
4705 self.exp = value[2]
4707 def __repr__(self):
4708 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4710 __str__ = __repr__
4714 def _normalize(op1, op2, prec = 0):
4715 """Normalizes op1, op2 to have the same exp and length of coefficient.
4717 Done during addition.
4719 if op1.exp < op2.exp:
4720 tmp = op2
4721 other = op1
4722 else:
4723 tmp = op1
4724 other = op2
4726 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4727 # Then adding 10**exp to tmp has the same effect (after rounding)
4728 # as adding any positive quantity smaller than 10**exp; similarly
4729 # for subtraction. So if other is smaller than 10**exp we replace
4730 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4731 tmp_len = len(str(tmp.int))
4732 other_len = len(str(other.int))
4733 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4734 if other_len + other.exp - 1 < exp:
4735 other.int = 1
4736 other.exp = exp
4738 tmp.int *= 10 ** (tmp.exp - other.exp)
4739 tmp.exp = other.exp
4740 return op1, op2
4742 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4744 # This function from Tim Peters was taken from here:
4745 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4746 # The correction being in the function definition is for speed, and
4747 # the whole function is not resolved with math.log because of avoiding
4748 # the use of floats.
4749 def _nbits(n, correction = {
4750 '0': 4, '1': 3, '2': 2, '3': 2,
4751 '4': 1, '5': 1, '6': 1, '7': 1,
4752 '8': 0, '9': 0, 'a': 0, 'b': 0,
4753 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4754 """Number of bits in binary representation of the positive integer n,
4755 or 0 if n == 0.
4757 if n < 0:
4758 raise ValueError("The argument to _nbits should be nonnegative.")
4759 hex_n = "%x" % n
4760 return 4*len(hex_n) - correction[hex_n[0]]
4762 def _sqrt_nearest(n, a):
4763 """Closest integer to the square root of the positive integer n. a is
4764 an initial approximation to the square root. Any positive integer
4765 will do for a, but the closer a is to the square root of n the
4766 faster convergence will be.
4769 if n <= 0 or a <= 0:
4770 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4773 while a != b:
4774 b, a = a, a--n//a>>1
4775 return a
4777 def _rshift_nearest(x, shift):
4778 """Given an integer x and a nonnegative integer shift, return closest
4779 integer to x / 2**shift; use round-to-even in case of a tie.
4782 b, q = 1L << shift, x >> shift
4783 return q + (2*(x & (b-1)) + (q&1) > b)
4785 def _div_nearest(a, b):
4786 """Closest integer to a/b, a and b positive integers; rounds to even
4787 in the case of a tie.
4790 q, r = divmod(a, b)
4791 return q + (2*r + (q&1) > b)
4793 def _ilog(x, M, L = 8):
4794 """Integer approximation to M*log(x/M), with absolute error boundable
4795 in terms only of x/M.
4797 Given positive integers x and M, return an integer approximation to
4798 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4799 between the approximation and the exact result is at most 22. For
4800 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4801 both cases these are upper bounds on the error; it will usually be
4802 much smaller."""
4804 # The basic algorithm is the following: let log1p be the function
4805 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4806 # the reduction
4808 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4810 # repeatedly until the argument to log1p is small (< 2**-L in
4811 # absolute value). For small y we can use the Taylor series
4812 # expansion
4814 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4816 # truncating at T such that y**T is small enough. The whole
4817 # computation is carried out in a form of fixed-point arithmetic,
4818 # with a real number z being represented by an integer
4819 # approximation to z*M. To avoid loss of precision, the y below
4820 # is actually an integer approximation to 2**R*y*M, where R is the
4821 # number of reductions performed so far.
4823 y = x-M
4824 # argument reduction; R = number of reductions performed
4825 R = 0
4826 while (R <= L and long(abs(y)) << L-R >= M or
4827 R > L and abs(y) >> R-L >= M):
4828 y = _div_nearest(long(M*y) << 1,
4829 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4830 R += 1
4832 # Taylor series with T terms
4833 T = -int(-10*len(str(M))//(3*L))
4834 yshift = _rshift_nearest(y, R)
4835 w = _div_nearest(M, T)
4836 for k in xrange(T-1, 0, -1):
4837 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4839 return _div_nearest(w*y, M)
4841 def _dlog10(c, e, p):
4842 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4843 approximation to 10**p * log10(c*10**e), with an absolute error of
4844 at most 1. Assumes that c*10**e is not exactly 1."""
4846 # increase precision by 2; compensate for this by dividing
4847 # final result by 100
4848 p += 2
4850 # write c*10**e as d*10**f with either:
4851 # f >= 0 and 1 <= d <= 10, or
4852 # f <= 0 and 0.1 <= d <= 1.
4853 # Thus for c*10**e close to 1, f = 0
4854 l = len(str(c))
4855 f = e+l - (e+l >= 1)
4857 if p > 0:
4858 M = 10**p
4859 k = e+p-f
4860 if k >= 0:
4861 c *= 10**k
4862 else:
4863 c = _div_nearest(c, 10**-k)
4865 log_d = _ilog(c, M) # error < 5 + 22 = 27
4866 log_10 = _log10_digits(p) # error < 1
4867 log_d = _div_nearest(log_d*M, log_10)
4868 log_tenpower = f*M # exact
4869 else:
4870 log_d = 0 # error < 2.31
4871 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4873 return _div_nearest(log_tenpower+log_d, 100)
4875 def _dlog(c, e, p):
4876 """Given integers c, e and p with c > 0, compute an integer
4877 approximation to 10**p * log(c*10**e), with an absolute error of
4878 at most 1. Assumes that c*10**e is not exactly 1."""
4880 # Increase precision by 2. The precision increase is compensated
4881 # for at the end with a division by 100.
4882 p += 2
4884 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4885 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4886 # as 10**p * log(d) + 10**p*f * log(10).
4887 l = len(str(c))
4888 f = e+l - (e+l >= 1)
4890 # compute approximation to 10**p*log(d), with error < 27
4891 if p > 0:
4892 k = e+p-f
4893 if k >= 0:
4894 c *= 10**k
4895 else:
4896 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4898 # _ilog magnifies existing error in c by a factor of at most 10
4899 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4900 else:
4901 # p <= 0: just approximate the whole thing by 0; error < 2.31
4902 log_d = 0
4904 # compute approximation to f*10**p*log(10), with error < 11.
4905 if f:
4906 extra = len(str(abs(f)))-1
4907 if p + extra >= 0:
4908 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4909 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4910 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4911 else:
4912 f_log_ten = 0
4913 else:
4914 f_log_ten = 0
4916 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4917 return _div_nearest(f_log_ten + log_d, 100)
4919 class _Log10Memoize(object):
4920 """Class to compute, store, and allow retrieval of, digits of the
4921 constant log(10) = 2.302585.... This constant is needed by
4922 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4923 def __init__(self):
4924 self.digits = "23025850929940456840179914546843642076011014886"
4926 def getdigits(self, p):
4927 """Given an integer p >= 0, return floor(10**p)*log(10).
4929 For example, self.getdigits(3) returns 2302.
4931 # digits are stored as a string, for quick conversion to
4932 # integer in the case that we've already computed enough
4933 # digits; the stored digits should always be correct
4934 # (truncated, not rounded to nearest).
4935 if p < 0:
4936 raise ValueError("p should be nonnegative")
4938 if p >= len(self.digits):
4939 # compute p+3, p+6, p+9, ... digits; continue until at
4940 # least one of the extra digits is nonzero
4941 extra = 3
4942 while True:
4943 # compute p+extra digits, correct to within 1ulp
4944 M = 10**(p+extra+2)
4945 digits = str(_div_nearest(_ilog(10*M, M), 100))
4946 if digits[-extra:] != '0'*extra:
4947 break
4948 extra += 3
4949 # keep all reliable digits so far; remove trailing zeros
4950 # and next nonzero digit
4951 self.digits = digits.rstrip('0')[:-1]
4952 return int(self.digits[:p+1])
4954 _log10_digits = _Log10Memoize().getdigits
4956 def _iexp(x, M, L=8):
4957 """Given integers x and M, M > 0, such that x/M is small in absolute
4958 value, compute an integer approximation to M*exp(x/M). For 0 <=
4959 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4960 is usually much smaller)."""
4962 # Algorithm: to compute exp(z) for a real number z, first divide z
4963 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4964 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4965 # series
4967 # expm1(x) = x + x**2/2! + x**3/3! + ...
4969 # Now use the identity
4971 # expm1(2x) = expm1(x)*(expm1(x)+2)
4973 # R times to compute the sequence expm1(z/2**R),
4974 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4976 # Find R such that x/2**R/M <= 2**-L
4977 R = _nbits((long(x)<<L)//M)
4979 # Taylor series. (2**L)**T > M
4980 T = -int(-10*len(str(M))//(3*L))
4981 y = _div_nearest(x, T)
4982 Mshift = long(M)<<R
4983 for i in xrange(T-1, 0, -1):
4984 y = _div_nearest(x*(Mshift + y), Mshift * i)
4986 # Expansion
4987 for k in xrange(R-1, -1, -1):
4988 Mshift = long(M)<<(k+2)
4989 y = _div_nearest(y*(y+Mshift), Mshift)
4991 return M+y
4993 def _dexp(c, e, p):
4994 """Compute an approximation to exp(c*10**e), with p decimal places of
4995 precision.
4997 Returns integers d, f such that:
4999 10**(p-1) <= d <= 10**p, and
5000 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5002 In other words, d*10**f is an approximation to exp(c*10**e) with p
5003 digits of precision, and with an error in d of at most 1. This is
5004 almost, but not quite, the same as the error being < 1ulp: when d
5005 = 10**(p-1) the error could be up to 10 ulp."""
5007 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5008 p += 2
5010 # compute log(10) with extra precision = adjusted exponent of c*10**e
5011 extra = max(0, e + len(str(c)) - 1)
5012 q = p + extra
5014 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5015 # rounding down
5016 shift = e+q
5017 if shift >= 0:
5018 cshift = c*10**shift
5019 else:
5020 cshift = c//10**-shift
5021 quot, rem = divmod(cshift, _log10_digits(q))
5023 # reduce remainder back to original precision
5024 rem = _div_nearest(rem, 10**extra)
5026 # error in result of _iexp < 120; error after division < 0.62
5027 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5029 def _dpower(xc, xe, yc, ye, p):
5030 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5031 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5033 10**(p-1) <= c <= 10**p, and
5034 (c-1)*10**e < x**y < (c+1)*10**e
5036 in other words, c*10**e is an approximation to x**y with p digits
5037 of precision, and with an error in c of at most 1. (This is
5038 almost, but not quite, the same as the error being < 1ulp: when c
5039 == 10**(p-1) we can only guarantee error < 10ulp.)
5041 We assume that: x is positive and not equal to 1, and y is nonzero.
5044 # Find b such that 10**(b-1) <= |y| <= 10**b
5045 b = len(str(abs(yc))) + ye
5047 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5048 lxc = _dlog(xc, xe, p+b+1)
5050 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5051 shift = ye-b
5052 if shift >= 0:
5053 pc = lxc*yc*10**shift
5054 else:
5055 pc = _div_nearest(lxc*yc, 10**-shift)
5057 if pc == 0:
5058 # we prefer a result that isn't exactly 1; this makes it
5059 # easier to compute a correctly rounded result in __pow__
5060 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5061 coeff, exp = 10**(p-1)+1, 1-p
5062 else:
5063 coeff, exp = 10**p-1, -p
5064 else:
5065 coeff, exp = _dexp(pc, -(p+1), p+1)
5066 coeff = _div_nearest(coeff, 10)
5067 exp += 1
5069 return coeff, exp
5071 def _log10_lb(c, correction = {
5072 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5073 '6': 23, '7': 16, '8': 10, '9': 5}):
5074 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5075 if c <= 0:
5076 raise ValueError("The argument to _log10_lb should be nonnegative.")
5077 str_c = str(c)
5078 return 100*len(str_c) - correction[str_c[0]]
5080 ##### Helper Functions ####################################################
5082 def _convert_other(other, raiseit=False):
5083 """Convert other to Decimal.
5085 Verifies that it's ok to use in an implicit construction.
5087 if isinstance(other, Decimal):
5088 return other
5089 if isinstance(other, (int, long)):
5090 return Decimal(other)
5091 if raiseit:
5092 raise TypeError("Unable to convert %s to Decimal" % other)
5093 return NotImplemented
5095 ##### Setup Specific Contexts ############################################
5097 # The default context prototype used by Context()
5098 # Is mutable, so that new contexts can have different default values
5100 DefaultContext = Context(
5101 prec=28, rounding=ROUND_HALF_EVEN,
5102 traps=[DivisionByZero, Overflow, InvalidOperation],
5103 flags=[],
5104 Emax=999999999,
5105 Emin=-999999999,
5106 capitals=1
5109 # Pre-made alternate contexts offered by the specification
5110 # Don't change these; the user should be able to select these
5111 # contexts and be able to reproduce results from other implementations
5112 # of the spec.
5114 BasicContext = Context(
5115 prec=9, rounding=ROUND_HALF_UP,
5116 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5117 flags=[],
5120 ExtendedContext = Context(
5121 prec=9, rounding=ROUND_HALF_EVEN,
5122 traps=[],
5123 flags=[],
5127 ##### crud for parsing strings #############################################
5128 import re
5130 # Regular expression used for parsing numeric strings. Additional
5131 # comments:
5133 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5134 # whitespace. But note that the specification disallows whitespace in
5135 # a numeric string.
5137 # 2. For finite numbers (not infinities and NaNs) the body of the
5138 # number between the optional sign and the optional exponent must have
5139 # at least one decimal digit, possibly after the decimal point. The
5140 # lookahead expression '(?=\d|\.\d)' checks this.
5142 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5143 # other meaning for \d than the numbers [0-9].
5145 import re
5146 _parser = re.compile(r""" # A numeric string consists of:
5147 # \s*
5148 (?P<sign>[-+])? # an optional sign, followed by either...
5150 (?=\d|\.\d) # ...a number (with at least one digit)
5151 (?P<int>\d*) # consisting of a (possibly empty) integer part
5152 (\.(?P<frac>\d*))? # followed by an optional fractional part
5153 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5155 Inf(inity)? # ...an infinity, or...
5157 (?P<signal>s)? # ...an (optionally signaling)
5158 NaN # NaN
5159 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5161 # \s*
5163 """, re.VERBOSE | re.IGNORECASE).match
5165 _all_zeros = re.compile('0*$').match
5166 _exact_half = re.compile('50*$').match
5167 del re
5170 ##### Useful Constants (internal use only) ################################
5172 # Reusable defaults
5173 Inf = Decimal('Inf')
5174 negInf = Decimal('-Inf')
5175 NaN = Decimal('NaN')
5176 Dec_0 = Decimal(0)
5177 Dec_p1 = Decimal(1)
5178 Dec_n1 = Decimal(-1)
5180 # Infsign[sign] is infinity w/ that sign
5181 Infsign = (Inf, negInf)
5185 if __name__ == '__main__':
5186 import doctest, sys
5187 doctest.testmod(sys.modules[__name__])