Fix the tag.
[python/dscho.git] / Lib / decimal.py
blobf008b5a2c2786b0a2d83290bf84325226dd773b1
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 decimal.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 decimal.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 numbers as _numbers
138 import copy as _copy
140 try:
141 from collections import namedtuple as _namedtuple
142 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
143 except ImportError:
144 DecimalTuple = lambda *args: args
146 # Rounding
147 ROUND_DOWN = 'ROUND_DOWN'
148 ROUND_HALF_UP = 'ROUND_HALF_UP'
149 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
150 ROUND_CEILING = 'ROUND_CEILING'
151 ROUND_FLOOR = 'ROUND_FLOOR'
152 ROUND_UP = 'ROUND_UP'
153 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
154 ROUND_05UP = 'ROUND_05UP'
156 # Errors
158 class DecimalException(ArithmeticError):
159 """Base exception class.
161 Used exceptions derive from this.
162 If an exception derives from another exception besides this (such as
163 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
164 called if the others are present. This isn't actually used for
165 anything, though.
167 handle -- Called when context._raise_error is called and the
168 trap_enabler is set. First argument is self, second is the
169 context. More arguments can be given, those being after
170 the explanation in _raise_error (For example,
171 context._raise_error(NewError, '(-x)!', self._sign) would
172 call NewError().handle(context, self._sign).)
174 To define a new exception, it should be sufficient to have it derive
175 from DecimalException.
177 def handle(self, context, *args):
178 pass
181 class Clamped(DecimalException):
182 """Exponent of a 0 changed to fit bounds.
184 This occurs and signals clamped if the exponent of a result has been
185 altered in order to fit the constraints of a specific concrete
186 representation. This may occur when the exponent of a zero result would
187 be outside the bounds of a representation, or when a large normal
188 number would have an encoded exponent that cannot be represented. In
189 this latter case, the exponent is reduced to fit and the corresponding
190 number of zero digits are appended to the coefficient ("fold-down").
193 class InvalidOperation(DecimalException):
194 """An invalid operation was performed.
196 Various bad things cause this:
198 Something creates a signaling NaN
199 -INF + INF
200 0 * (+-)INF
201 (+-)INF / (+-)INF
202 x % 0
203 (+-)INF % x
204 x._rescale( non-integer )
205 sqrt(-x) , x > 0
206 0 ** 0
207 x ** (non-integer)
208 x ** (+-)INF
209 An operand is invalid
211 The result of the operation after these is a quiet positive NaN,
212 except when the cause is a signaling NaN, in which case the result is
213 also a quiet NaN, but with the original sign, and an optional
214 diagnostic information.
216 def handle(self, context, *args):
217 if args:
218 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
219 return ans._fix_nan(context)
220 return NaN
222 class ConversionSyntax(InvalidOperation):
223 """Trying to convert badly formed string.
225 This occurs and signals invalid-operation if an string is being
226 converted to a number and it does not conform to the numeric string
227 syntax. The result is [0,qNaN].
229 def handle(self, context, *args):
230 return NaN
232 class DivisionByZero(DecimalException, ZeroDivisionError):
233 """Division by 0.
235 This occurs and signals division-by-zero if division of a finite number
236 by zero was attempted (during a divide-integer or divide operation, or a
237 power operation with negative right-hand operand), and the dividend was
238 not zero.
240 The result of the operation is [sign,inf], where sign is the exclusive
241 or of the signs of the operands for divide, or is 1 for an odd power of
242 -0, for power.
245 def handle(self, context, sign, *args):
246 return Infsign[sign]
248 class DivisionImpossible(InvalidOperation):
249 """Cannot perform the division adequately.
251 This occurs and signals invalid-operation if the integer result of a
252 divide-integer or remainder operation had too many digits (would be
253 longer than precision). The result is [0,qNaN].
256 def handle(self, context, *args):
257 return NaN
259 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
260 """Undefined result of division.
262 This occurs and signals invalid-operation if division by zero was
263 attempted (during a divide-integer, divide, or remainder operation), and
264 the dividend is also zero. The result is [0,qNaN].
267 def handle(self, context, *args):
268 return NaN
270 class Inexact(DecimalException):
271 """Had to round, losing information.
273 This occurs and signals inexact whenever the result of an operation is
274 not exact (that is, it needed to be rounded and any discarded digits
275 were non-zero), or if an overflow or underflow condition occurs. The
276 result in all cases is unchanged.
278 The inexact signal may be tested (or trapped) to determine if a given
279 operation (or sequence of operations) was inexact.
282 class InvalidContext(InvalidOperation):
283 """Invalid context. Unknown rounding, for example.
285 This occurs and signals invalid-operation if an invalid context was
286 detected during an operation. This can occur if contexts are not checked
287 on creation and either the precision exceeds the capability of the
288 underlying concrete representation or an unknown or unsupported rounding
289 was specified. These aspects of the context need only be checked when
290 the values are required to be used. The result is [0,qNaN].
293 def handle(self, context, *args):
294 return NaN
296 class Rounded(DecimalException):
297 """Number got rounded (not necessarily changed during rounding).
299 This occurs and signals rounded whenever the result of an operation is
300 rounded (that is, some zero or non-zero digits were discarded from the
301 coefficient), or if an overflow or underflow condition occurs. The
302 result in all cases is unchanged.
304 The rounded signal may be tested (or trapped) to determine if a given
305 operation (or sequence of operations) caused a loss of precision.
308 class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
313 Emin, before any rounding). The result in all cases is unchanged.
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
319 class Overflow(Inexact, Rounded):
320 """Numerical overflow.
322 This occurs and signals overflow if the adjusted exponent of a result
323 (from a conversion or from an operation that is not an attempt to divide
324 by zero), after rounding, would be greater than the largest value that
325 can be handled by the implementation (the value Emax).
327 The result depends on the rounding mode:
329 For round-half-up and round-half-even (and for round-half-down and
330 round-up, if implemented), the result of the operation is [sign,inf],
331 where sign is the sign of the intermediate result. For round-down, the
332 result is the largest finite number that can be represented in the
333 current precision, with the sign of the intermediate result. For
334 round-ceiling, the result is the same as for round-down if the sign of
335 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
336 the result is the same as for round-down if the sign of the intermediate
337 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
338 will also be raised.
341 def handle(self, context, sign, *args):
342 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
343 ROUND_HALF_DOWN, ROUND_UP):
344 return Infsign[sign]
345 if sign == 0:
346 if context.rounding == ROUND_CEILING:
347 return Infsign[sign]
348 return _dec_from_triple(sign, '9'*context.prec,
349 context.Emax-context.prec+1)
350 if sign == 1:
351 if context.rounding == ROUND_FLOOR:
352 return Infsign[sign]
353 return _dec_from_triple(sign, '9'*context.prec,
354 context.Emax-context.prec+1)
357 class Underflow(Inexact, Rounded, Subnormal):
358 """Numerical underflow with result rounded to 0.
360 This occurs and signals underflow if a result is inexact and the
361 adjusted exponent of the result would be smaller (more negative) than
362 the smallest value that can be handled by the implementation (the value
363 Emin). That is, the result is both inexact and subnormal.
365 The result after an underflow will be a subnormal number rounded, if
366 necessary, so that its exponent is not less than Etiny. This may result
367 in 0 with the sign of the intermediate result and an exponent of Etiny.
369 In all cases, Inexact, Rounded, and Subnormal will also be raised.
372 # List of public traps and flags
373 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
374 Underflow, InvalidOperation, Subnormal]
376 # Map conditions (per the spec) to signals
377 _condition_map = {ConversionSyntax:InvalidOperation,
378 DivisionImpossible:InvalidOperation,
379 DivisionUndefined:InvalidOperation,
380 InvalidContext:InvalidOperation}
382 ##### Context Functions ##################################################
384 # The getcontext() and setcontext() function manage access to a thread-local
385 # current context. Py2.4 offers direct support for thread locals. If that
386 # is not available, use threading.currentThread() which is slower but will
387 # work for older Pythons. If threads are not part of the build, create a
388 # mock threading object with threading.local() returning the module namespace.
390 try:
391 import threading
392 except ImportError:
393 # Python was compiled without threads; create a mock object instead
394 import sys
395 class MockThreading(object):
396 def local(self, sys=sys):
397 return sys.modules[__name__]
398 threading = MockThreading()
399 del sys, MockThreading
401 try:
402 threading.local
404 except AttributeError:
406 # To fix reloading, force it to create a new context
407 # Old contexts have different exceptions in their dicts, making problems.
408 if hasattr(threading.currentThread(), '__decimal_context__'):
409 del threading.currentThread().__decimal_context__
411 def setcontext(context):
412 """Set this thread's context to context."""
413 if context in (DefaultContext, BasicContext, ExtendedContext):
414 context = context.copy()
415 context.clear_flags()
416 threading.currentThread().__decimal_context__ = context
418 def getcontext():
419 """Returns this thread's context.
421 If this thread does not yet have a context, returns
422 a new context and sets this thread's context.
423 New contexts are copies of DefaultContext.
425 try:
426 return threading.currentThread().__decimal_context__
427 except AttributeError:
428 context = Context()
429 threading.currentThread().__decimal_context__ = context
430 return context
432 else:
434 local = threading.local()
435 if hasattr(local, '__decimal_context__'):
436 del local.__decimal_context__
438 def getcontext(_local=local):
439 """Returns this thread's context.
441 If this thread does not yet have a context, returns
442 a new context and sets this thread's context.
443 New contexts are copies of DefaultContext.
445 try:
446 return _local.__decimal_context__
447 except AttributeError:
448 context = Context()
449 _local.__decimal_context__ = context
450 return context
452 def setcontext(context, _local=local):
453 """Set this thread's context to context."""
454 if context in (DefaultContext, BasicContext, ExtendedContext):
455 context = context.copy()
456 context.clear_flags()
457 _local.__decimal_context__ = context
459 del threading, local # Don't contaminate the namespace
461 def localcontext(ctx=None):
462 """Return a context manager for a copy of the supplied context
464 Uses a copy of the current context if no context is specified
465 The returned context manager creates a local decimal context
466 in a with statement:
467 def sin(x):
468 with localcontext() as ctx:
469 ctx.prec += 2
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
472 return +s # Convert result to normal precision
474 def sin(x):
475 with localcontext(ExtendedContext):
476 # Rest of sin calculation algorithm
477 # uses the Extended Context from the
478 # General Decimal Arithmetic Specification
479 return +s # Convert result to normal context
481 >>> setcontext(DefaultContext)
482 >>> print(getcontext().prec)
484 >>> with localcontext():
485 ... ctx = getcontext()
486 ... ctx.prec += 2
487 ... print(ctx.prec)
490 >>> with localcontext(ExtendedContext):
491 ... print(getcontext().prec)
494 >>> print(getcontext().prec)
497 if ctx is None: ctx = getcontext()
498 return _ContextManager(ctx)
501 ##### Decimal class #######################################################
503 class Decimal(_numbers.Real):
504 """Floating point class for decimal arithmetic."""
506 __slots__ = ('_exp','_int','_sign', '_is_special')
507 # Generally, the value of the Decimal instance is given by
508 # (-1)**_sign * _int * 10**_exp
509 # Special values are signified by _is_special == True
511 # We're immutable, so use __new__ not __init__
512 def __new__(cls, value="0", context=None):
513 """Create a decimal point instance.
515 >>> Decimal('3.14') # string input
516 Decimal('3.14')
517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
518 Decimal('3.14')
519 >>> Decimal(314) # int
520 Decimal('314')
521 >>> Decimal(Decimal(314)) # another decimal instance
522 Decimal('314')
523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
524 Decimal('3.14')
527 # Note that the coefficient, self._int, is actually stored as
528 # a string rather than as a tuple of digits. This speeds up
529 # the "digits to integer" and "integer to digits" conversions
530 # that are used in almost every arithmetic operation on
531 # Decimals. This is an internal detail: the as_tuple function
532 # and the Decimal constructor still deal with tuples of
533 # digits.
535 self = object.__new__(cls)
537 # From a string
538 # REs insist on real strings, so we can too.
539 if isinstance(value, str):
540 m = _parser(value.strip())
541 if m is None:
542 if context is None:
543 context = getcontext()
544 return context._raise_error(ConversionSyntax,
545 "Invalid literal for Decimal: %r" % value)
547 if m.group('sign') == "-":
548 self._sign = 1
549 else:
550 self._sign = 0
551 intpart = m.group('int')
552 if intpart is not None:
553 # finite number
554 fracpart = m.group('frac')
555 exp = int(m.group('exp') or '0')
556 if fracpart is not None:
557 self._int = (intpart+fracpart).lstrip('0') or '0'
558 self._exp = exp - len(fracpart)
559 else:
560 self._int = intpart.lstrip('0') or '0'
561 self._exp = exp
562 self._is_special = False
563 else:
564 diag = m.group('diag')
565 if diag is not None:
566 # NaN
567 self._int = diag.lstrip('0')
568 if m.group('signal'):
569 self._exp = 'N'
570 else:
571 self._exp = 'n'
572 else:
573 # infinity
574 self._int = '0'
575 self._exp = 'F'
576 self._is_special = True
577 return self
579 # From an integer
580 if isinstance(value, int):
581 if value >= 0:
582 self._sign = 0
583 else:
584 self._sign = 1
585 self._exp = 0
586 self._int = str(abs(value))
587 self._is_special = False
588 return self
590 # From another decimal
591 if isinstance(value, Decimal):
592 self._exp = value._exp
593 self._sign = value._sign
594 self._int = value._int
595 self._is_special = value._is_special
596 return self
598 # From an internal working value
599 if isinstance(value, _WorkRep):
600 self._sign = value.sign
601 self._int = str(value.int)
602 self._exp = int(value.exp)
603 self._is_special = False
604 return self
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value, (list,tuple)):
608 if len(value) != 3:
609 raise ValueError('Invalid tuple size in creation of Decimal '
610 'from list or tuple. The list or tuple '
611 'should have exactly three elements.')
612 # process sign. The isinstance test rejects floats
613 if not (isinstance(value[0], int) and value[0] in (0,1)):
614 raise ValueError("Invalid sign. The first value in the tuple "
615 "should be an integer; either 0 for a "
616 "positive number or 1 for a negative number.")
617 self._sign = value[0]
618 if value[2] == 'F':
619 # infinity: value[1] is ignored
620 self._int = '0'
621 self._exp = value[2]
622 self._is_special = True
623 else:
624 # process and validate the digits in value[1]
625 digits = []
626 for digit in value[1]:
627 if isinstance(digit, int) and 0 <= digit <= 9:
628 # skip leading zeros
629 if digits or digit != 0:
630 digits.append(digit)
631 else:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
634 "0 through 9.")
635 if value[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
637 self._int = ''.join(map(str, digits))
638 self._exp = value[2]
639 self._is_special = True
640 elif isinstance(value[2], int):
641 # finite number: digits give the coefficient
642 self._int = ''.join(map(str, digits or [0]))
643 self._exp = value[2]
644 self._is_special = False
645 else:
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
649 return self
651 if isinstance(value, float):
652 raise TypeError("Cannot convert float to Decimal. " +
653 "First convert the float to a string")
655 raise TypeError("Cannot convert %r to Decimal" % value)
657 def _isnan(self):
658 """Returns whether the number is not actually one.
660 0 if a number
661 1 if NaN
662 2 if sNaN
664 if self._is_special:
665 exp = self._exp
666 if exp == 'n':
667 return 1
668 elif exp == 'N':
669 return 2
670 return 0
672 def _isinfinity(self):
673 """Returns whether the number is infinite
675 0 if finite or not a number
676 1 if +INF
677 -1 if -INF
679 if self._exp == 'F':
680 if self._sign:
681 return -1
682 return 1
683 return 0
685 def _check_nans(self, other=None, context=None):
686 """Returns whether the number is not actually one.
688 if self, other are sNaN, signal
689 if self, other are NaN return nan
690 return 0
692 Done before operations.
695 self_is_nan = self._isnan()
696 if other is None:
697 other_is_nan = False
698 else:
699 other_is_nan = other._isnan()
701 if self_is_nan or other_is_nan:
702 if context is None:
703 context = getcontext()
705 if self_is_nan == 2:
706 return context._raise_error(InvalidOperation, 'sNaN',
707 self)
708 if other_is_nan == 2:
709 return context._raise_error(InvalidOperation, 'sNaN',
710 other)
711 if self_is_nan:
712 return self._fix_nan(context)
714 return other._fix_nan(context)
715 return 0
717 def _compare_check_nans(self, other, context):
718 """Version of _check_nans used for the signaling comparisons
719 compare_signal, __le__, __lt__, __ge__, __gt__.
721 Signal InvalidOperation if either self or other is a (quiet
722 or signaling) NaN. Signaling NaNs take precedence over quiet
723 NaNs.
725 Return 0 if neither operand is a NaN.
728 if context is None:
729 context = getcontext()
731 if self._is_special or other._is_special:
732 if self.is_snan():
733 return context._raise_error(InvalidOperation,
734 'comparison involving sNaN',
735 self)
736 elif other.is_snan():
737 return context._raise_error(InvalidOperation,
738 'comparison involving sNaN',
739 other)
740 elif self.is_qnan():
741 return context._raise_error(InvalidOperation,
742 'comparison involving NaN',
743 self)
744 elif other.is_qnan():
745 return context._raise_error(InvalidOperation,
746 'comparison involving NaN',
747 other)
748 return 0
750 def __bool__(self):
751 """Return True if self is nonzero; otherwise return False.
753 NaNs and infinities are considered nonzero.
755 return self._is_special or self._int != '0'
757 def _cmp(self, other):
758 """Compare the two non-NaN decimal instances self and other.
760 Returns -1 if self < other, 0 if self == other and 1
761 if self > other. This routine is for internal use only."""
763 if self._is_special or other._is_special:
764 return cmp(self._isinfinity(), other._isinfinity())
766 # check for zeros; note that cmp(0, -0) should return 0
767 if not self:
768 if not other:
769 return 0
770 else:
771 return -((-1)**other._sign)
772 if not other:
773 return (-1)**self._sign
775 # If different signs, neg one is less
776 if other._sign < self._sign:
777 return -1
778 if self._sign < other._sign:
779 return 1
781 self_adjusted = self.adjusted()
782 other_adjusted = other.adjusted()
783 if self_adjusted == other_adjusted:
784 self_padded = self._int + '0'*(self._exp - other._exp)
785 other_padded = other._int + '0'*(other._exp - self._exp)
786 return cmp(self_padded, other_padded) * (-1)**self._sign
787 elif self_adjusted > other_adjusted:
788 return (-1)**self._sign
789 else: # self_adjusted < other_adjusted
790 return -((-1)**self._sign)
792 # Note: The Decimal standard doesn't cover rich comparisons for
793 # Decimals. In particular, the specification is silent on the
794 # subject of what should happen for a comparison involving a NaN.
795 # We take the following approach:
797 # == comparisons involving a NaN always return False
798 # != comparisons involving a NaN always return True
799 # <, >, <= and >= comparisons involving a (quiet or signaling)
800 # NaN signal InvalidOperation, and return False if the
801 # InvalidOperation is not trapped.
803 # This behavior is designed to conform as closely as possible to
804 # that specified by IEEE 754.
806 def __eq__(self, other):
807 other = _convert_other(other)
808 if other is NotImplemented:
809 return other
810 if self.is_nan() or other.is_nan():
811 return False
812 return self._cmp(other) == 0
814 def __ne__(self, other):
815 other = _convert_other(other)
816 if other is NotImplemented:
817 return other
818 if self.is_nan() or other.is_nan():
819 return True
820 return self._cmp(other) != 0
823 def __lt__(self, other, context=None):
824 other = _convert_other(other)
825 if other is NotImplemented:
826 return other
827 ans = self._compare_check_nans(other, context)
828 if ans:
829 return False
830 return self._cmp(other) < 0
832 def __le__(self, other, context=None):
833 other = _convert_other(other)
834 if other is NotImplemented:
835 return other
836 ans = self._compare_check_nans(other, context)
837 if ans:
838 return False
839 return self._cmp(other) <= 0
841 def __gt__(self, other, context=None):
842 other = _convert_other(other)
843 if other is NotImplemented:
844 return other
845 ans = self._compare_check_nans(other, context)
846 if ans:
847 return False
848 return self._cmp(other) > 0
850 def __ge__(self, other, context=None):
851 other = _convert_other(other)
852 if other is NotImplemented:
853 return other
854 ans = self._compare_check_nans(other, context)
855 if ans:
856 return False
857 return self._cmp(other) >= 0
859 def compare(self, other, context=None):
860 """Compares one to another.
862 -1 => a < b
863 0 => a = b
864 1 => a > b
865 NaN => one is NaN
866 Like __cmp__, but returns Decimal instances.
868 other = _convert_other(other, raiseit=True)
870 # Compare(NaN, NaN) = NaN
871 if (self._is_special or other and other._is_special):
872 ans = self._check_nans(other, context)
873 if ans:
874 return ans
876 return Decimal(self._cmp(other))
878 def __hash__(self):
879 """x.__hash__() <==> hash(x)"""
880 # Decimal integers must hash the same as the ints
882 # The hash of a nonspecial noninteger Decimal must depend only
883 # on the value of that Decimal, and not on its representation.
884 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
885 if self._is_special:
886 if self._isnan():
887 raise TypeError('Cannot hash a NaN value.')
888 return hash(str(self))
889 if not self:
890 return 0
891 if self._isinteger():
892 op = _WorkRep(self.to_integral_value())
893 # to make computation feasible for Decimals with large
894 # exponent, we use the fact that hash(n) == hash(m) for
895 # any two nonzero integers n and m such that (i) n and m
896 # have the same sign, and (ii) n is congruent to m modulo
897 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
898 # hash((-1)**s*c*pow(10, e, 2**64-1).
899 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
900 # The value of a nonzero nonspecial Decimal instance is
901 # faithfully represented by the triple consisting of its sign,
902 # its adjusted exponent, and its coefficient with trailing
903 # zeros removed.
904 return hash((self._sign,
905 self._exp+len(self._int),
906 self._int.rstrip('0')))
908 def as_tuple(self):
909 """Represents the number as a triple tuple.
911 To show the internals exactly as they are.
913 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
915 def __repr__(self):
916 """Represents the number as an instance of Decimal."""
917 # Invariant: eval(repr(d)) == d
918 return "Decimal('%s')" % str(self)
920 def __str__(self, eng=False, context=None):
921 """Return string representation of the number in scientific notation.
923 Captures all of the information in the underlying representation.
926 sign = ['', '-'][self._sign]
927 if self._is_special:
928 if self._exp == 'F':
929 return sign + 'Infinity'
930 elif self._exp == 'n':
931 return sign + 'NaN' + self._int
932 else: # self._exp == 'N'
933 return sign + 'sNaN' + self._int
935 # number of digits of self._int to left of decimal point
936 leftdigits = self._exp + len(self._int)
938 # dotplace is number of digits of self._int to the left of the
939 # decimal point in the mantissa of the output string (that is,
940 # after adjusting the exponent)
941 if self._exp <= 0 and leftdigits > -6:
942 # no exponent required
943 dotplace = leftdigits
944 elif not eng:
945 # usual scientific notation: 1 digit on left of the point
946 dotplace = 1
947 elif self._int == '0':
948 # engineering notation, zero
949 dotplace = (leftdigits + 1) % 3 - 1
950 else:
951 # engineering notation, nonzero
952 dotplace = (leftdigits - 1) % 3 + 1
954 if dotplace <= 0:
955 intpart = '0'
956 fracpart = '.' + '0'*(-dotplace) + self._int
957 elif dotplace >= len(self._int):
958 intpart = self._int+'0'*(dotplace-len(self._int))
959 fracpart = ''
960 else:
961 intpart = self._int[:dotplace]
962 fracpart = '.' + self._int[dotplace:]
963 if leftdigits == dotplace:
964 exp = ''
965 else:
966 if context is None:
967 context = getcontext()
968 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
970 return sign + intpart + fracpart + exp
972 def to_eng_string(self, context=None):
973 """Convert to engineering-type string.
975 Engineering notation has an exponent which is a multiple of 3, so there
976 are up to 3 digits left of the decimal place.
978 Same rules for when in exponential and when as a value as in __str__.
980 return self.__str__(eng=True, context=context)
982 def __neg__(self, context=None):
983 """Returns a copy with the sign switched.
985 Rounds, if it has reason.
987 if self._is_special:
988 ans = self._check_nans(context=context)
989 if ans:
990 return ans
992 if not self:
993 # -Decimal('0') is Decimal('0'), not Decimal('-0')
994 ans = self.copy_abs()
995 else:
996 ans = self.copy_negate()
998 if context is None:
999 context = getcontext()
1000 return ans._fix(context)
1002 def __pos__(self, context=None):
1003 """Returns a copy, unless it is a sNaN.
1005 Rounds the number (if more then precision digits)
1007 if self._is_special:
1008 ans = self._check_nans(context=context)
1009 if ans:
1010 return ans
1012 if not self:
1013 # + (-0) = 0
1014 ans = self.copy_abs()
1015 else:
1016 ans = Decimal(self)
1018 if context is None:
1019 context = getcontext()
1020 return ans._fix(context)
1022 def __abs__(self, round=True, context=None):
1023 """Returns the absolute value of self.
1025 If the keyword argument 'round' is false, do not round. The
1026 expression self.__abs__(round=False) is equivalent to
1027 self.copy_abs().
1029 if not round:
1030 return self.copy_abs()
1032 if self._is_special:
1033 ans = self._check_nans(context=context)
1034 if ans:
1035 return ans
1037 if self._sign:
1038 ans = self.__neg__(context=context)
1039 else:
1040 ans = self.__pos__(context=context)
1042 return ans
1044 def __add__(self, other, context=None):
1045 """Returns self + other.
1047 -INF + INF (or the reverse) cause InvalidOperation errors.
1049 other = _convert_other(other)
1050 if other is NotImplemented:
1051 return other
1053 if context is None:
1054 context = getcontext()
1056 if self._is_special or other._is_special:
1057 ans = self._check_nans(other, context)
1058 if ans:
1059 return ans
1061 if self._isinfinity():
1062 # If both INF, same sign => same as both, opposite => error.
1063 if self._sign != other._sign and other._isinfinity():
1064 return context._raise_error(InvalidOperation, '-INF + INF')
1065 return Decimal(self)
1066 if other._isinfinity():
1067 return Decimal(other) # Can't both be infinity here
1069 exp = min(self._exp, other._exp)
1070 negativezero = 0
1071 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1072 # If the answer is 0, the sign should be negative, in this case.
1073 negativezero = 1
1075 if not self and not other:
1076 sign = min(self._sign, other._sign)
1077 if negativezero:
1078 sign = 1
1079 ans = _dec_from_triple(sign, '0', exp)
1080 ans = ans._fix(context)
1081 return ans
1082 if not self:
1083 exp = max(exp, other._exp - context.prec-1)
1084 ans = other._rescale(exp, context.rounding)
1085 ans = ans._fix(context)
1086 return ans
1087 if not other:
1088 exp = max(exp, self._exp - context.prec-1)
1089 ans = self._rescale(exp, context.rounding)
1090 ans = ans._fix(context)
1091 return ans
1093 op1 = _WorkRep(self)
1094 op2 = _WorkRep(other)
1095 op1, op2 = _normalize(op1, op2, context.prec)
1097 result = _WorkRep()
1098 if op1.sign != op2.sign:
1099 # Equal and opposite
1100 if op1.int == op2.int:
1101 ans = _dec_from_triple(negativezero, '0', exp)
1102 ans = ans._fix(context)
1103 return ans
1104 if op1.int < op2.int:
1105 op1, op2 = op2, op1
1106 # OK, now abs(op1) > abs(op2)
1107 if op1.sign == 1:
1108 result.sign = 1
1109 op1.sign, op2.sign = op2.sign, op1.sign
1110 else:
1111 result.sign = 0
1112 # So we know the sign, and op1 > 0.
1113 elif op1.sign == 1:
1114 result.sign = 1
1115 op1.sign, op2.sign = (0, 0)
1116 else:
1117 result.sign = 0
1118 # Now, op1 > abs(op2) > 0
1120 if op2.sign == 0:
1121 result.int = op1.int + op2.int
1122 else:
1123 result.int = op1.int - op2.int
1125 result.exp = op1.exp
1126 ans = Decimal(result)
1127 ans = ans._fix(context)
1128 return ans
1130 __radd__ = __add__
1132 def __sub__(self, other, context=None):
1133 """Return self - other"""
1134 other = _convert_other(other)
1135 if other is NotImplemented:
1136 return other
1138 if self._is_special or other._is_special:
1139 ans = self._check_nans(other, context=context)
1140 if ans:
1141 return ans
1143 # self - other is computed as self + other.copy_negate()
1144 return self.__add__(other.copy_negate(), context=context)
1146 def __rsub__(self, other, context=None):
1147 """Return other - self"""
1148 other = _convert_other(other)
1149 if other is NotImplemented:
1150 return other
1152 return other.__sub__(self, context=context)
1154 def __mul__(self, other, context=None):
1155 """Return self * other.
1157 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1159 other = _convert_other(other)
1160 if other is NotImplemented:
1161 return other
1163 if context is None:
1164 context = getcontext()
1166 resultsign = self._sign ^ other._sign
1168 if self._is_special or other._is_special:
1169 ans = self._check_nans(other, context)
1170 if ans:
1171 return ans
1173 if self._isinfinity():
1174 if not other:
1175 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1176 return Infsign[resultsign]
1178 if other._isinfinity():
1179 if not self:
1180 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1181 return Infsign[resultsign]
1183 resultexp = self._exp + other._exp
1185 # Special case for multiplying by zero
1186 if not self or not other:
1187 ans = _dec_from_triple(resultsign, '0', resultexp)
1188 # Fixing in case the exponent is out of bounds
1189 ans = ans._fix(context)
1190 return ans
1192 # Special case for multiplying by power of 10
1193 if self._int == '1':
1194 ans = _dec_from_triple(resultsign, other._int, resultexp)
1195 ans = ans._fix(context)
1196 return ans
1197 if other._int == '1':
1198 ans = _dec_from_triple(resultsign, self._int, resultexp)
1199 ans = ans._fix(context)
1200 return ans
1202 op1 = _WorkRep(self)
1203 op2 = _WorkRep(other)
1205 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1206 ans = ans._fix(context)
1208 return ans
1209 __rmul__ = __mul__
1211 def __truediv__(self, other, context=None):
1212 """Return self / other."""
1213 other = _convert_other(other)
1214 if other is NotImplemented:
1215 return NotImplemented
1217 if context is None:
1218 context = getcontext()
1220 sign = self._sign ^ other._sign
1222 if self._is_special or other._is_special:
1223 ans = self._check_nans(other, context)
1224 if ans:
1225 return ans
1227 if self._isinfinity() and other._isinfinity():
1228 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1230 if self._isinfinity():
1231 return Infsign[sign]
1233 if other._isinfinity():
1234 context._raise_error(Clamped, 'Division by infinity')
1235 return _dec_from_triple(sign, '0', context.Etiny())
1237 # Special cases for zeroes
1238 if not other:
1239 if not self:
1240 return context._raise_error(DivisionUndefined, '0 / 0')
1241 return context._raise_error(DivisionByZero, 'x / 0', sign)
1243 if not self:
1244 exp = self._exp - other._exp
1245 coeff = 0
1246 else:
1247 # OK, so neither = 0, INF or NaN
1248 shift = len(other._int) - len(self._int) + context.prec + 1
1249 exp = self._exp - other._exp - shift
1250 op1 = _WorkRep(self)
1251 op2 = _WorkRep(other)
1252 if shift >= 0:
1253 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1254 else:
1255 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1256 if remainder:
1257 # result is not exact; adjust to ensure correct rounding
1258 if coeff % 5 == 0:
1259 coeff += 1
1260 else:
1261 # result is exact; get as close to ideal exponent as possible
1262 ideal_exp = self._exp - other._exp
1263 while exp < ideal_exp and coeff % 10 == 0:
1264 coeff //= 10
1265 exp += 1
1267 ans = _dec_from_triple(sign, str(coeff), exp)
1268 return ans._fix(context)
1270 def _divide(self, other, context):
1271 """Return (self // other, self % other), to context.prec precision.
1273 Assumes that neither self nor other is a NaN, that self is not
1274 infinite and that other is nonzero.
1276 sign = self._sign ^ other._sign
1277 if other._isinfinity():
1278 ideal_exp = self._exp
1279 else:
1280 ideal_exp = min(self._exp, other._exp)
1282 expdiff = self.adjusted() - other.adjusted()
1283 if not self or other._isinfinity() or expdiff <= -2:
1284 return (_dec_from_triple(sign, '0', 0),
1285 self._rescale(ideal_exp, context.rounding))
1286 if expdiff <= context.prec:
1287 op1 = _WorkRep(self)
1288 op2 = _WorkRep(other)
1289 if op1.exp >= op2.exp:
1290 op1.int *= 10**(op1.exp - op2.exp)
1291 else:
1292 op2.int *= 10**(op2.exp - op1.exp)
1293 q, r = divmod(op1.int, op2.int)
1294 if q < 10**context.prec:
1295 return (_dec_from_triple(sign, str(q), 0),
1296 _dec_from_triple(self._sign, str(r), ideal_exp))
1298 # Here the quotient is too large to be representable
1299 ans = context._raise_error(DivisionImpossible,
1300 'quotient too large in //, % or divmod')
1301 return ans, ans
1303 def __rtruediv__(self, other, context=None):
1304 """Swaps self/other and returns __truediv__."""
1305 other = _convert_other(other)
1306 if other is NotImplemented:
1307 return other
1308 return other.__truediv__(self, context=context)
1310 def __divmod__(self, other, context=None):
1312 Return (self // other, self % other)
1314 other = _convert_other(other)
1315 if other is NotImplemented:
1316 return other
1318 if context is None:
1319 context = getcontext()
1321 ans = self._check_nans(other, context)
1322 if ans:
1323 return (ans, ans)
1325 sign = self._sign ^ other._sign
1326 if self._isinfinity():
1327 if other._isinfinity():
1328 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1329 return ans, ans
1330 else:
1331 return (Infsign[sign],
1332 context._raise_error(InvalidOperation, 'INF % x'))
1334 if not other:
1335 if not self:
1336 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1337 return ans, ans
1338 else:
1339 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1340 context._raise_error(InvalidOperation, 'x % 0'))
1342 quotient, remainder = self._divide(other, context)
1343 remainder = remainder._fix(context)
1344 return quotient, remainder
1346 def __rdivmod__(self, other, context=None):
1347 """Swaps self/other and returns __divmod__."""
1348 other = _convert_other(other)
1349 if other is NotImplemented:
1350 return other
1351 return other.__divmod__(self, context=context)
1353 def __mod__(self, other, context=None):
1355 self % other
1357 other = _convert_other(other)
1358 if other is NotImplemented:
1359 return other
1361 if context is None:
1362 context = getcontext()
1364 ans = self._check_nans(other, context)
1365 if ans:
1366 return ans
1368 if self._isinfinity():
1369 return context._raise_error(InvalidOperation, 'INF % x')
1370 elif not other:
1371 if self:
1372 return context._raise_error(InvalidOperation, 'x % 0')
1373 else:
1374 return context._raise_error(DivisionUndefined, '0 % 0')
1376 remainder = self._divide(other, context)[1]
1377 remainder = remainder._fix(context)
1378 return remainder
1380 def __rmod__(self, other, context=None):
1381 """Swaps self/other and returns __mod__."""
1382 other = _convert_other(other)
1383 if other is NotImplemented:
1384 return other
1385 return other.__mod__(self, context=context)
1387 def remainder_near(self, other, context=None):
1389 Remainder nearest to 0- abs(remainder-near) <= other/2
1391 if context is None:
1392 context = getcontext()
1394 other = _convert_other(other, raiseit=True)
1396 ans = self._check_nans(other, context)
1397 if ans:
1398 return ans
1400 # self == +/-infinity -> InvalidOperation
1401 if self._isinfinity():
1402 return context._raise_error(InvalidOperation,
1403 'remainder_near(infinity, x)')
1405 # other == 0 -> either InvalidOperation or DivisionUndefined
1406 if not other:
1407 if self:
1408 return context._raise_error(InvalidOperation,
1409 'remainder_near(x, 0)')
1410 else:
1411 return context._raise_error(DivisionUndefined,
1412 'remainder_near(0, 0)')
1414 # other = +/-infinity -> remainder = self
1415 if other._isinfinity():
1416 ans = Decimal(self)
1417 return ans._fix(context)
1419 # self = 0 -> remainder = self, with ideal exponent
1420 ideal_exponent = min(self._exp, other._exp)
1421 if not self:
1422 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1423 return ans._fix(context)
1425 # catch most cases of large or small quotient
1426 expdiff = self.adjusted() - other.adjusted()
1427 if expdiff >= context.prec + 1:
1428 # expdiff >= prec+1 => abs(self/other) > 10**prec
1429 return context._raise_error(DivisionImpossible)
1430 if expdiff <= -2:
1431 # expdiff <= -2 => abs(self/other) < 0.1
1432 ans = self._rescale(ideal_exponent, context.rounding)
1433 return ans._fix(context)
1435 # adjust both arguments to have the same exponent, then divide
1436 op1 = _WorkRep(self)
1437 op2 = _WorkRep(other)
1438 if op1.exp >= op2.exp:
1439 op1.int *= 10**(op1.exp - op2.exp)
1440 else:
1441 op2.int *= 10**(op2.exp - op1.exp)
1442 q, r = divmod(op1.int, op2.int)
1443 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1444 # 10**ideal_exponent. Apply correction to ensure that
1445 # abs(remainder) <= abs(other)/2
1446 if 2*r + (q&1) > op2.int:
1447 r -= op2.int
1448 q += 1
1450 if q >= 10**context.prec:
1451 return context._raise_error(DivisionImpossible)
1453 # result has same sign as self unless r is negative
1454 sign = self._sign
1455 if r < 0:
1456 sign = 1-sign
1457 r = -r
1459 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1460 return ans._fix(context)
1462 def __floordiv__(self, other, context=None):
1463 """self // other"""
1464 other = _convert_other(other)
1465 if other is NotImplemented:
1466 return other
1468 if context is None:
1469 context = getcontext()
1471 ans = self._check_nans(other, context)
1472 if ans:
1473 return ans
1475 if self._isinfinity():
1476 if other._isinfinity():
1477 return context._raise_error(InvalidOperation, 'INF // INF')
1478 else:
1479 return Infsign[self._sign ^ other._sign]
1481 if not other:
1482 if self:
1483 return context._raise_error(DivisionByZero, 'x // 0',
1484 self._sign ^ other._sign)
1485 else:
1486 return context._raise_error(DivisionUndefined, '0 // 0')
1488 return self._divide(other, context)[0]
1490 def __rfloordiv__(self, other, context=None):
1491 """Swaps self/other and returns __floordiv__."""
1492 other = _convert_other(other)
1493 if other is NotImplemented:
1494 return other
1495 return other.__floordiv__(self, context=context)
1497 def __float__(self):
1498 """Float representation."""
1499 return float(str(self))
1501 def __int__(self):
1502 """Converts self to an int, truncating if necessary."""
1503 if self._is_special:
1504 if self._isnan():
1505 context = getcontext()
1506 return context._raise_error(InvalidContext)
1507 elif self._isinfinity():
1508 raise OverflowError("Cannot convert infinity to int")
1509 s = (-1)**self._sign
1510 if self._exp >= 0:
1511 return s*int(self._int)*10**self._exp
1512 else:
1513 return s*int(self._int[:self._exp] or '0')
1515 __trunc__ = __int__
1517 @property
1518 def real(self):
1519 return self
1521 @property
1522 def imag(self):
1523 return Decimal(0)
1525 def conjugate(self):
1526 return self
1528 def __complex__(self):
1529 return complex(float(self))
1531 def _fix_nan(self, context):
1532 """Decapitate the payload of a NaN to fit the context"""
1533 payload = self._int
1535 # maximum length of payload is precision if _clamp=0,
1536 # precision-1 if _clamp=1.
1537 max_payload_len = context.prec - context._clamp
1538 if len(payload) > max_payload_len:
1539 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1540 return _dec_from_triple(self._sign, payload, self._exp, True)
1541 return Decimal(self)
1543 def _fix(self, context):
1544 """Round if it is necessary to keep self within prec precision.
1546 Rounds and fixes the exponent. Does not raise on a sNaN.
1548 Arguments:
1549 self - Decimal instance
1550 context - context used.
1553 if self._is_special:
1554 if self._isnan():
1555 # decapitate payload if necessary
1556 return self._fix_nan(context)
1557 else:
1558 # self is +/-Infinity; return unaltered
1559 return Decimal(self)
1561 # if self is zero then exponent should be between Etiny and
1562 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1563 Etiny = context.Etiny()
1564 Etop = context.Etop()
1565 if not self:
1566 exp_max = [context.Emax, Etop][context._clamp]
1567 new_exp = min(max(self._exp, Etiny), exp_max)
1568 if new_exp != self._exp:
1569 context._raise_error(Clamped)
1570 return _dec_from_triple(self._sign, '0', new_exp)
1571 else:
1572 return Decimal(self)
1574 # exp_min is the smallest allowable exponent of the result,
1575 # equal to max(self.adjusted()-context.prec+1, Etiny)
1576 exp_min = len(self._int) + self._exp - context.prec
1577 if exp_min > Etop:
1578 # overflow: exp_min > Etop iff self.adjusted() > Emax
1579 context._raise_error(Inexact)
1580 context._raise_error(Rounded)
1581 return context._raise_error(Overflow, 'above Emax', self._sign)
1582 self_is_subnormal = exp_min < Etiny
1583 if self_is_subnormal:
1584 context._raise_error(Subnormal)
1585 exp_min = Etiny
1587 # round if self has too many digits
1588 if self._exp < exp_min:
1589 context._raise_error(Rounded)
1590 digits = len(self._int) + self._exp - exp_min
1591 if digits < 0:
1592 self = _dec_from_triple(self._sign, '1', exp_min-1)
1593 digits = 0
1594 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1595 changed = this_function(digits)
1596 coeff = self._int[:digits] or '0'
1597 if changed == 1:
1598 coeff = str(int(coeff)+1)
1599 ans = _dec_from_triple(self._sign, coeff, exp_min)
1601 if changed:
1602 context._raise_error(Inexact)
1603 if self_is_subnormal:
1604 context._raise_error(Underflow)
1605 if not ans:
1606 # raise Clamped on underflow to 0
1607 context._raise_error(Clamped)
1608 elif len(ans._int) == context.prec+1:
1609 # we get here only if rescaling rounds the
1610 # cofficient up to exactly 10**context.prec
1611 if ans._exp < Etop:
1612 ans = _dec_from_triple(ans._sign,
1613 ans._int[:-1], ans._exp+1)
1614 else:
1615 # Inexact and Rounded have already been raised
1616 ans = context._raise_error(Overflow, 'above Emax',
1617 self._sign)
1618 return ans
1620 # fold down if _clamp == 1 and self has too few digits
1621 if context._clamp == 1 and self._exp > Etop:
1622 context._raise_error(Clamped)
1623 self_padded = self._int + '0'*(self._exp - Etop)
1624 return _dec_from_triple(self._sign, self_padded, Etop)
1626 # here self was representable to begin with; return unchanged
1627 return Decimal(self)
1629 _pick_rounding_function = {}
1631 # for each of the rounding functions below:
1632 # self is a finite, nonzero Decimal
1633 # prec is an integer satisfying 0 <= prec < len(self._int)
1635 # each function returns either -1, 0, or 1, as follows:
1636 # 1 indicates that self should be rounded up (away from zero)
1637 # 0 indicates that self should be truncated, and that all the
1638 # digits to be truncated are zeros (so the value is unchanged)
1639 # -1 indicates that there are nonzero digits to be truncated
1641 def _round_down(self, prec):
1642 """Also known as round-towards-0, truncate."""
1643 if _all_zeros(self._int, prec):
1644 return 0
1645 else:
1646 return -1
1648 def __round__(self):
1649 return self._round_down(0)
1651 def _round_up(self, prec):
1652 """Rounds away from 0."""
1653 return -self._round_down(prec)
1655 def _round_half_up(self, prec):
1656 """Rounds 5 up (away from 0)"""
1657 if self._int[prec] in '56789':
1658 return 1
1659 elif _all_zeros(self._int, prec):
1660 return 0
1661 else:
1662 return -1
1664 def _round_half_down(self, prec):
1665 """Round 5 down"""
1666 if _exact_half(self._int, prec):
1667 return -1
1668 else:
1669 return self._round_half_up(prec)
1671 def _round_half_even(self, prec):
1672 """Round 5 to even, rest to nearest."""
1673 if _exact_half(self._int, prec) and \
1674 (prec == 0 or self._int[prec-1] in '02468'):
1675 return -1
1676 else:
1677 return self._round_half_up(prec)
1679 def _round_ceiling(self, prec):
1680 """Rounds up (not away from 0 if negative.)"""
1681 if self._sign:
1682 return self._round_down(prec)
1683 else:
1684 return -self._round_down(prec)
1686 def __ceil__(self):
1687 return self._round_ceiling(0)
1689 def _round_floor(self, prec):
1690 """Rounds down (not towards 0 if negative)"""
1691 if not self._sign:
1692 return self._round_down(prec)
1693 else:
1694 return -self._round_down(prec)
1696 def __floor__(self):
1697 return self._round_floor(0)
1699 def _round_05up(self, prec):
1700 """Round down unless digit prec-1 is 0 or 5."""
1701 if prec and self._int[prec-1] not in '05':
1702 return self._round_down(prec)
1703 else:
1704 return -self._round_down(prec)
1706 def fma(self, other, third, context=None):
1707 """Fused multiply-add.
1709 Returns self*other+third with no rounding of the intermediate
1710 product self*other.
1712 self and other are multiplied together, with no rounding of
1713 the result. The third operand is then added to the result,
1714 and a single final rounding is performed.
1717 other = _convert_other(other, raiseit=True)
1719 # compute product; raise InvalidOperation if either operand is
1720 # a signaling NaN or if the product is zero times infinity.
1721 if self._is_special or other._is_special:
1722 if context is None:
1723 context = getcontext()
1724 if self._exp == 'N':
1725 return context._raise_error(InvalidOperation, 'sNaN', self)
1726 if other._exp == 'N':
1727 return context._raise_error(InvalidOperation, 'sNaN', other)
1728 if self._exp == 'n':
1729 product = self
1730 elif other._exp == 'n':
1731 product = other
1732 elif self._exp == 'F':
1733 if not other:
1734 return context._raise_error(InvalidOperation,
1735 'INF * 0 in fma')
1736 product = Infsign[self._sign ^ other._sign]
1737 elif other._exp == 'F':
1738 if not self:
1739 return context._raise_error(InvalidOperation,
1740 '0 * INF in fma')
1741 product = Infsign[self._sign ^ other._sign]
1742 else:
1743 product = _dec_from_triple(self._sign ^ other._sign,
1744 str(int(self._int) * int(other._int)),
1745 self._exp + other._exp)
1747 third = _convert_other(third, raiseit=True)
1748 return product.__add__(third, context)
1750 def _power_modulo(self, other, modulo, context=None):
1751 """Three argument version of __pow__"""
1753 # if can't convert other and modulo to Decimal, raise
1754 # TypeError; there's no point returning NotImplemented (no
1755 # equivalent of __rpow__ for three argument pow)
1756 other = _convert_other(other, raiseit=True)
1757 modulo = _convert_other(modulo, raiseit=True)
1759 if context is None:
1760 context = getcontext()
1762 # deal with NaNs: if there are any sNaNs then first one wins,
1763 # (i.e. behaviour for NaNs is identical to that of fma)
1764 self_is_nan = self._isnan()
1765 other_is_nan = other._isnan()
1766 modulo_is_nan = modulo._isnan()
1767 if self_is_nan or other_is_nan or modulo_is_nan:
1768 if self_is_nan == 2:
1769 return context._raise_error(InvalidOperation, 'sNaN',
1770 self)
1771 if other_is_nan == 2:
1772 return context._raise_error(InvalidOperation, 'sNaN',
1773 other)
1774 if modulo_is_nan == 2:
1775 return context._raise_error(InvalidOperation, 'sNaN',
1776 modulo)
1777 if self_is_nan:
1778 return self._fix_nan(context)
1779 if other_is_nan:
1780 return other._fix_nan(context)
1781 return modulo._fix_nan(context)
1783 # check inputs: we apply same restrictions as Python's pow()
1784 if not (self._isinteger() and
1785 other._isinteger() and
1786 modulo._isinteger()):
1787 return context._raise_error(InvalidOperation,
1788 'pow() 3rd argument not allowed '
1789 'unless all arguments are integers')
1790 if other < 0:
1791 return context._raise_error(InvalidOperation,
1792 'pow() 2nd argument cannot be '
1793 'negative when 3rd argument specified')
1794 if not modulo:
1795 return context._raise_error(InvalidOperation,
1796 'pow() 3rd argument cannot be 0')
1798 # additional restriction for decimal: the modulus must be less
1799 # than 10**prec in absolute value
1800 if modulo.adjusted() >= context.prec:
1801 return context._raise_error(InvalidOperation,
1802 'insufficient precision: pow() 3rd '
1803 'argument must not have more than '
1804 'precision digits')
1806 # define 0**0 == NaN, for consistency with two-argument pow
1807 # (even though it hurts!)
1808 if not other and not self:
1809 return context._raise_error(InvalidOperation,
1810 'at least one of pow() 1st argument '
1811 'and 2nd argument must be nonzero ;'
1812 '0**0 is not defined')
1814 # compute sign of result
1815 if other._iseven():
1816 sign = 0
1817 else:
1818 sign = self._sign
1820 # convert modulo to a Python integer, and self and other to
1821 # Decimal integers (i.e. force their exponents to be >= 0)
1822 modulo = abs(int(modulo))
1823 base = _WorkRep(self.to_integral_value())
1824 exponent = _WorkRep(other.to_integral_value())
1826 # compute result using integer pow()
1827 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1828 for i in range(exponent.exp):
1829 base = pow(base, 10, modulo)
1830 base = pow(base, exponent.int, modulo)
1832 return _dec_from_triple(sign, str(base), 0)
1834 def _power_exact(self, other, p):
1835 """Attempt to compute self**other exactly.
1837 Given Decimals self and other and an integer p, attempt to
1838 compute an exact result for the power self**other, with p
1839 digits of precision. Return None if self**other is not
1840 exactly representable in p digits.
1842 Assumes that elimination of special cases has already been
1843 performed: self and other must both be nonspecial; self must
1844 be positive and not numerically equal to 1; other must be
1845 nonzero. For efficiency, other._exp should not be too large,
1846 so that 10**abs(other._exp) is a feasible calculation."""
1848 # In the comments below, we write x for the value of self and
1849 # y for the value of other. Write x = xc*10**xe and y =
1850 # yc*10**ye.
1852 # The main purpose of this method is to identify the *failure*
1853 # of x**y to be exactly representable with as little effort as
1854 # possible. So we look for cheap and easy tests that
1855 # eliminate the possibility of x**y being exact. Only if all
1856 # these tests are passed do we go on to actually compute x**y.
1858 # Here's the main idea. First normalize both x and y. We
1859 # express y as a rational m/n, with m and n relatively prime
1860 # and n>0. Then for x**y to be exactly representable (at
1861 # *any* precision), xc must be the nth power of a positive
1862 # integer and xe must be divisible by n. If m is negative
1863 # then additionally xc must be a power of either 2 or 5, hence
1864 # a power of 2**n or 5**n.
1866 # There's a limit to how small |y| can be: if y=m/n as above
1867 # then:
1869 # (1) if xc != 1 then for the result to be representable we
1870 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1871 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1872 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1873 # representable.
1875 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1876 # |y| < 1/|xe| then the result is not representable.
1878 # Note that since x is not equal to 1, at least one of (1) and
1879 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1880 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1882 # There's also a limit to how large y can be, at least if it's
1883 # positive: the normalized result will have coefficient xc**y,
1884 # so if it's representable then xc**y < 10**p, and y <
1885 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1886 # not exactly representable.
1888 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1889 # so |y| < 1/xe and the result is not representable.
1890 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1891 # < 1/nbits(xc).
1893 x = _WorkRep(self)
1894 xc, xe = x.int, x.exp
1895 while xc % 10 == 0:
1896 xc //= 10
1897 xe += 1
1899 y = _WorkRep(other)
1900 yc, ye = y.int, y.exp
1901 while yc % 10 == 0:
1902 yc //= 10
1903 ye += 1
1905 # case where xc == 1: result is 10**(xe*y), with xe*y
1906 # required to be an integer
1907 if xc == 1:
1908 if ye >= 0:
1909 exponent = xe*yc*10**ye
1910 else:
1911 exponent, remainder = divmod(xe*yc, 10**-ye)
1912 if remainder:
1913 return None
1914 if y.sign == 1:
1915 exponent = -exponent
1916 # if other is a nonnegative integer, use ideal exponent
1917 if other._isinteger() and other._sign == 0:
1918 ideal_exponent = self._exp*int(other)
1919 zeros = min(exponent-ideal_exponent, p-1)
1920 else:
1921 zeros = 0
1922 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1924 # case where y is negative: xc must be either a power
1925 # of 2 or a power of 5.
1926 if y.sign == 1:
1927 last_digit = xc % 10
1928 if last_digit in (2,4,6,8):
1929 # quick test for power of 2
1930 if xc & -xc != xc:
1931 return None
1932 # now xc is a power of 2; e is its exponent
1933 e = _nbits(xc)-1
1934 # find e*y and xe*y; both must be integers
1935 if ye >= 0:
1936 y_as_int = yc*10**ye
1937 e = e*y_as_int
1938 xe = xe*y_as_int
1939 else:
1940 ten_pow = 10**-ye
1941 e, remainder = divmod(e*yc, ten_pow)
1942 if remainder:
1943 return None
1944 xe, remainder = divmod(xe*yc, ten_pow)
1945 if remainder:
1946 return None
1948 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1949 return None
1950 xc = 5**e
1952 elif last_digit == 5:
1953 # e >= log_5(xc) if xc is a power of 5; we have
1954 # equality all the way up to xc=5**2658
1955 e = _nbits(xc)*28//65
1956 xc, remainder = divmod(5**e, xc)
1957 if remainder:
1958 return None
1959 while xc % 5 == 0:
1960 xc //= 5
1961 e -= 1
1962 if ye >= 0:
1963 y_as_integer = yc*10**ye
1964 e = e*y_as_integer
1965 xe = xe*y_as_integer
1966 else:
1967 ten_pow = 10**-ye
1968 e, remainder = divmod(e*yc, ten_pow)
1969 if remainder:
1970 return None
1971 xe, remainder = divmod(xe*yc, ten_pow)
1972 if remainder:
1973 return None
1974 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1975 return None
1976 xc = 2**e
1977 else:
1978 return None
1980 if xc >= 10**p:
1981 return None
1982 xe = -e-xe
1983 return _dec_from_triple(0, str(xc), xe)
1985 # now y is positive; find m and n such that y = m/n
1986 if ye >= 0:
1987 m, n = yc*10**ye, 1
1988 else:
1989 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1990 return None
1991 xc_bits = _nbits(xc)
1992 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1993 return None
1994 m, n = yc, 10**(-ye)
1995 while m % 2 == n % 2 == 0:
1996 m //= 2
1997 n //= 2
1998 while m % 5 == n % 5 == 0:
1999 m //= 5
2000 n //= 5
2002 # compute nth root of xc*10**xe
2003 if n > 1:
2004 # if 1 < xc < 2**n then xc isn't an nth power
2005 if xc != 1 and xc_bits <= n:
2006 return None
2008 xe, rem = divmod(xe, n)
2009 if rem != 0:
2010 return None
2012 # compute nth root of xc using Newton's method
2013 a = 1 << -(-_nbits(xc)//n) # initial estimate
2014 while True:
2015 q, r = divmod(xc, a**(n-1))
2016 if a <= q:
2017 break
2018 else:
2019 a = (a*(n-1) + q)//n
2020 if not (a == q and r == 0):
2021 return None
2022 xc = a
2024 # now xc*10**xe is the nth root of the original xc*10**xe
2025 # compute mth power of xc*10**xe
2027 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2028 # 10**p and the result is not representable.
2029 if xc > 1 and m > p*100//_log10_lb(xc):
2030 return None
2031 xc = xc**m
2032 xe *= m
2033 if xc > 10**p:
2034 return None
2036 # by this point the result *is* exactly representable
2037 # adjust the exponent to get as close as possible to the ideal
2038 # exponent, if necessary
2039 str_xc = str(xc)
2040 if other._isinteger() and other._sign == 0:
2041 ideal_exponent = self._exp*int(other)
2042 zeros = min(xe-ideal_exponent, p-len(str_xc))
2043 else:
2044 zeros = 0
2045 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2047 def __pow__(self, other, modulo=None, context=None):
2048 """Return self ** other [ % modulo].
2050 With two arguments, compute self**other.
2052 With three arguments, compute (self**other) % modulo. For the
2053 three argument form, the following restrictions on the
2054 arguments hold:
2056 - all three arguments must be integral
2057 - other must be nonnegative
2058 - either self or other (or both) must be nonzero
2059 - modulo must be nonzero and must have at most p digits,
2060 where p is the context precision.
2062 If any of these restrictions is violated the InvalidOperation
2063 flag is raised.
2065 The result of pow(self, other, modulo) is identical to the
2066 result that would be obtained by computing (self**other) %
2067 modulo with unbounded precision, but is computed more
2068 efficiently. It is always exact.
2071 if modulo is not None:
2072 return self._power_modulo(other, modulo, context)
2074 other = _convert_other(other)
2075 if other is NotImplemented:
2076 return other
2078 if context is None:
2079 context = getcontext()
2081 # either argument is a NaN => result is NaN
2082 ans = self._check_nans(other, context)
2083 if ans:
2084 return ans
2086 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2087 if not other:
2088 if not self:
2089 return context._raise_error(InvalidOperation, '0 ** 0')
2090 else:
2091 return Dec_p1
2093 # result has sign 1 iff self._sign is 1 and other is an odd integer
2094 result_sign = 0
2095 if self._sign == 1:
2096 if other._isinteger():
2097 if not other._iseven():
2098 result_sign = 1
2099 else:
2100 # -ve**noninteger = NaN
2101 # (-0)**noninteger = 0**noninteger
2102 if self:
2103 return context._raise_error(InvalidOperation,
2104 'x ** y with x negative and y not an integer')
2105 # negate self, without doing any unwanted rounding
2106 self = self.copy_negate()
2108 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2109 if not self:
2110 if other._sign == 0:
2111 return _dec_from_triple(result_sign, '0', 0)
2112 else:
2113 return Infsign[result_sign]
2115 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2116 if self._isinfinity():
2117 if other._sign == 0:
2118 return Infsign[result_sign]
2119 else:
2120 return _dec_from_triple(result_sign, '0', 0)
2122 # 1**other = 1, but the choice of exponent and the flags
2123 # depend on the exponent of self, and on whether other is a
2124 # positive integer, a negative integer, or neither
2125 if self == Dec_p1:
2126 if other._isinteger():
2127 # exp = max(self._exp*max(int(other), 0),
2128 # 1-context.prec) but evaluating int(other) directly
2129 # is dangerous until we know other is small (other
2130 # could be 1e999999999)
2131 if other._sign == 1:
2132 multiplier = 0
2133 elif other > context.prec:
2134 multiplier = context.prec
2135 else:
2136 multiplier = int(other)
2138 exp = self._exp * multiplier
2139 if exp < 1-context.prec:
2140 exp = 1-context.prec
2141 context._raise_error(Rounded)
2142 else:
2143 context._raise_error(Inexact)
2144 context._raise_error(Rounded)
2145 exp = 1-context.prec
2147 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2149 # compute adjusted exponent of self
2150 self_adj = self.adjusted()
2152 # self ** infinity is infinity if self > 1, 0 if self < 1
2153 # self ** -infinity is infinity if self < 1, 0 if self > 1
2154 if other._isinfinity():
2155 if (other._sign == 0) == (self_adj < 0):
2156 return _dec_from_triple(result_sign, '0', 0)
2157 else:
2158 return Infsign[result_sign]
2160 # from here on, the result always goes through the call
2161 # to _fix at the end of this function.
2162 ans = None
2164 # crude test to catch cases of extreme overflow/underflow. If
2165 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2166 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2167 # self**other >= 10**(Emax+1), so overflow occurs. The test
2168 # for underflow is similar.
2169 bound = self._log10_exp_bound() + other.adjusted()
2170 if (self_adj >= 0) == (other._sign == 0):
2171 # self > 1 and other +ve, or self < 1 and other -ve
2172 # possibility of overflow
2173 if bound >= len(str(context.Emax)):
2174 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2175 else:
2176 # self > 1 and other -ve, or self < 1 and other +ve
2177 # possibility of underflow to 0
2178 Etiny = context.Etiny()
2179 if bound >= len(str(-Etiny)):
2180 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2182 # try for an exact result with precision +1
2183 if ans is None:
2184 ans = self._power_exact(other, context.prec + 1)
2185 if ans is not None and result_sign == 1:
2186 ans = _dec_from_triple(1, ans._int, ans._exp)
2188 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2189 if ans is None:
2190 p = context.prec
2191 x = _WorkRep(self)
2192 xc, xe = x.int, x.exp
2193 y = _WorkRep(other)
2194 yc, ye = y.int, y.exp
2195 if y.sign == 1:
2196 yc = -yc
2198 # compute correctly rounded result: start with precision +3,
2199 # then increase precision until result is unambiguously roundable
2200 extra = 3
2201 while True:
2202 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2203 if coeff % (5*10**(len(str(coeff))-p-1)):
2204 break
2205 extra += 3
2207 ans = _dec_from_triple(result_sign, str(coeff), exp)
2209 # the specification says that for non-integer other we need to
2210 # raise Inexact, even when the result is actually exact. In
2211 # the same way, we need to raise Underflow here if the result
2212 # is subnormal. (The call to _fix will take care of raising
2213 # Rounded and Subnormal, as usual.)
2214 if not other._isinteger():
2215 context._raise_error(Inexact)
2216 # pad with zeros up to length context.prec+1 if necessary
2217 if len(ans._int) <= context.prec:
2218 expdiff = context.prec+1 - len(ans._int)
2219 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2220 ans._exp-expdiff)
2221 if ans.adjusted() < context.Emin:
2222 context._raise_error(Underflow)
2224 # unlike exp, ln and log10, the power function respects the
2225 # rounding mode; no need to use ROUND_HALF_EVEN here
2226 ans = ans._fix(context)
2227 return ans
2229 def __rpow__(self, other, context=None):
2230 """Swaps self/other and returns __pow__."""
2231 other = _convert_other(other)
2232 if other is NotImplemented:
2233 return other
2234 return other.__pow__(self, context=context)
2236 def normalize(self, context=None):
2237 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2239 if context is None:
2240 context = getcontext()
2242 if self._is_special:
2243 ans = self._check_nans(context=context)
2244 if ans:
2245 return ans
2247 dup = self._fix(context)
2248 if dup._isinfinity():
2249 return dup
2251 if not dup:
2252 return _dec_from_triple(dup._sign, '0', 0)
2253 exp_max = [context.Emax, context.Etop()][context._clamp]
2254 end = len(dup._int)
2255 exp = dup._exp
2256 while dup._int[end-1] == '0' and exp < exp_max:
2257 exp += 1
2258 end -= 1
2259 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2261 def quantize(self, exp, rounding=None, context=None, watchexp=True):
2262 """Quantize self so its exponent is the same as that of exp.
2264 Similar to self._rescale(exp._exp) but with error checking.
2266 exp = _convert_other(exp, raiseit=True)
2268 if context is None:
2269 context = getcontext()
2270 if rounding is None:
2271 rounding = context.rounding
2273 if self._is_special or exp._is_special:
2274 ans = self._check_nans(exp, context)
2275 if ans:
2276 return ans
2278 if exp._isinfinity() or self._isinfinity():
2279 if exp._isinfinity() and self._isinfinity():
2280 return Decimal(self) # if both are inf, it is OK
2281 return context._raise_error(InvalidOperation,
2282 'quantize with one INF')
2284 # if we're not watching exponents, do a simple rescale
2285 if not watchexp:
2286 ans = self._rescale(exp._exp, rounding)
2287 # raise Inexact and Rounded where appropriate
2288 if ans._exp > self._exp:
2289 context._raise_error(Rounded)
2290 if ans != self:
2291 context._raise_error(Inexact)
2292 return ans
2294 # exp._exp should be between Etiny and Emax
2295 if not (context.Etiny() <= exp._exp <= context.Emax):
2296 return context._raise_error(InvalidOperation,
2297 'target exponent out of bounds in quantize')
2299 if not self:
2300 ans = _dec_from_triple(self._sign, '0', exp._exp)
2301 return ans._fix(context)
2303 self_adjusted = self.adjusted()
2304 if self_adjusted > context.Emax:
2305 return context._raise_error(InvalidOperation,
2306 'exponent of quantize result too large for current context')
2307 if self_adjusted - exp._exp + 1 > context.prec:
2308 return context._raise_error(InvalidOperation,
2309 'quantize result has too many digits for current context')
2311 ans = self._rescale(exp._exp, rounding)
2312 if ans.adjusted() > context.Emax:
2313 return context._raise_error(InvalidOperation,
2314 'exponent of quantize result too large for current context')
2315 if len(ans._int) > context.prec:
2316 return context._raise_error(InvalidOperation,
2317 'quantize result has too many digits for current context')
2319 # raise appropriate flags
2320 if ans._exp > self._exp:
2321 context._raise_error(Rounded)
2322 if ans != self:
2323 context._raise_error(Inexact)
2324 if ans and ans.adjusted() < context.Emin:
2325 context._raise_error(Subnormal)
2327 # call to fix takes care of any necessary folddown
2328 ans = ans._fix(context)
2329 return ans
2331 def same_quantum(self, other):
2332 """Return True if self and other have the same exponent; otherwise
2333 return False.
2335 If either operand is a special value, the following rules are used:
2336 * return True if both operands are infinities
2337 * return True if both operands are NaNs
2338 * otherwise, return False.
2340 other = _convert_other(other, raiseit=True)
2341 if self._is_special or other._is_special:
2342 return (self.is_nan() and other.is_nan() or
2343 self.is_infinite() and other.is_infinite())
2344 return self._exp == other._exp
2346 def _rescale(self, exp, rounding):
2347 """Rescale self so that the exponent is exp, either by padding with zeros
2348 or by truncating digits, using the given rounding mode.
2350 Specials are returned without change. This operation is
2351 quiet: it raises no flags, and uses no information from the
2352 context.
2354 exp = exp to scale to (an integer)
2355 rounding = rounding mode
2357 if self._is_special:
2358 return Decimal(self)
2359 if not self:
2360 return _dec_from_triple(self._sign, '0', exp)
2362 if self._exp >= exp:
2363 # pad answer with zeros if necessary
2364 return _dec_from_triple(self._sign,
2365 self._int + '0'*(self._exp - exp), exp)
2367 # too many digits; round and lose data. If self.adjusted() <
2368 # exp-1, replace self by 10**(exp-1) before rounding
2369 digits = len(self._int) + self._exp - exp
2370 if digits < 0:
2371 self = _dec_from_triple(self._sign, '1', exp-1)
2372 digits = 0
2373 this_function = getattr(self, self._pick_rounding_function[rounding])
2374 changed = this_function(digits)
2375 coeff = self._int[:digits] or '0'
2376 if changed == 1:
2377 coeff = str(int(coeff)+1)
2378 return _dec_from_triple(self._sign, coeff, exp)
2380 def _round(self, places, rounding):
2381 """Round a nonzero, nonspecial Decimal to a fixed number of
2382 significant figures, using the given rounding mode.
2384 Infinities, NaNs and zeros are returned unaltered.
2386 This operation is quiet: it raises no flags, and uses no
2387 information from the context.
2390 if places <= 0:
2391 raise ValueError("argument should be at least 1 in _round")
2392 if self._is_special or not self:
2393 return Decimal(self)
2394 ans = self._rescale(self.adjusted()+1-places, rounding)
2395 # it can happen that the rescale alters the adjusted exponent;
2396 # for example when rounding 99.97 to 3 significant figures.
2397 # When this happens we end up with an extra 0 at the end of
2398 # the number; a second rescale fixes this.
2399 if ans.adjusted() != self.adjusted():
2400 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2401 return ans
2403 def to_integral_exact(self, rounding=None, context=None):
2404 """Rounds to a nearby integer.
2406 If no rounding mode is specified, take the rounding mode from
2407 the context. This method raises the Rounded and Inexact flags
2408 when appropriate.
2410 See also: to_integral_value, which does exactly the same as
2411 this method except that it doesn't raise Inexact or Rounded.
2413 if self._is_special:
2414 ans = self._check_nans(context=context)
2415 if ans:
2416 return ans
2417 return Decimal(self)
2418 if self._exp >= 0:
2419 return Decimal(self)
2420 if not self:
2421 return _dec_from_triple(self._sign, '0', 0)
2422 if context is None:
2423 context = getcontext()
2424 if rounding is None:
2425 rounding = context.rounding
2426 context._raise_error(Rounded)
2427 ans = self._rescale(0, rounding)
2428 if ans != self:
2429 context._raise_error(Inexact)
2430 return ans
2432 def to_integral_value(self, rounding=None, context=None):
2433 """Rounds to the nearest integer, without raising inexact, rounded."""
2434 if context is None:
2435 context = getcontext()
2436 if rounding is None:
2437 rounding = context.rounding
2438 if self._is_special:
2439 ans = self._check_nans(context=context)
2440 if ans:
2441 return ans
2442 return Decimal(self)
2443 if self._exp >= 0:
2444 return Decimal(self)
2445 else:
2446 return self._rescale(0, rounding)
2448 # the method name changed, but we provide also the old one, for compatibility
2449 to_integral = to_integral_value
2451 def sqrt(self, context=None):
2452 """Return the square root of self."""
2453 if context is None:
2454 context = getcontext()
2456 if self._is_special:
2457 ans = self._check_nans(context=context)
2458 if ans:
2459 return ans
2461 if self._isinfinity() and self._sign == 0:
2462 return Decimal(self)
2464 if not self:
2465 # exponent = self._exp // 2. sqrt(-0) = -0
2466 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2467 return ans._fix(context)
2469 if self._sign == 1:
2470 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2472 # At this point self represents a positive number. Let p be
2473 # the desired precision and express self in the form c*100**e
2474 # with c a positive real number and e an integer, c and e
2475 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2476 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2477 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2478 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2479 # the closest integer to sqrt(c) with the even integer chosen
2480 # in the case of a tie.
2482 # To ensure correct rounding in all cases, we use the
2483 # following trick: we compute the square root to an extra
2484 # place (precision p+1 instead of precision p), rounding down.
2485 # Then, if the result is inexact and its last digit is 0 or 5,
2486 # we increase the last digit to 1 or 6 respectively; if it's
2487 # exact we leave the last digit alone. Now the final round to
2488 # p places (or fewer in the case of underflow) will round
2489 # correctly and raise the appropriate flags.
2491 # use an extra digit of precision
2492 prec = context.prec+1
2494 # write argument in the form c*100**e where e = self._exp//2
2495 # is the 'ideal' exponent, to be used if the square root is
2496 # exactly representable. l is the number of 'digits' of c in
2497 # base 100, so that 100**(l-1) <= c < 100**l.
2498 op = _WorkRep(self)
2499 e = op.exp >> 1
2500 if op.exp & 1:
2501 c = op.int * 10
2502 l = (len(self._int) >> 1) + 1
2503 else:
2504 c = op.int
2505 l = len(self._int)+1 >> 1
2507 # rescale so that c has exactly prec base 100 'digits'
2508 shift = prec-l
2509 if shift >= 0:
2510 c *= 100**shift
2511 exact = True
2512 else:
2513 c, remainder = divmod(c, 100**-shift)
2514 exact = not remainder
2515 e -= shift
2517 # find n = floor(sqrt(c)) using Newton's method
2518 n = 10**prec
2519 while True:
2520 q = c//n
2521 if n <= q:
2522 break
2523 else:
2524 n = n + q >> 1
2525 exact = exact and n*n == c
2527 if exact:
2528 # result is exact; rescale to use ideal exponent e
2529 if shift >= 0:
2530 # assert n % 10**shift == 0
2531 n //= 10**shift
2532 else:
2533 n *= 10**-shift
2534 e += shift
2535 else:
2536 # result is not exact; fix last digit as described above
2537 if n % 5 == 0:
2538 n += 1
2540 ans = _dec_from_triple(0, str(n), e)
2542 # round, and fit to current context
2543 context = context._shallow_copy()
2544 rounding = context._set_rounding(ROUND_HALF_EVEN)
2545 ans = ans._fix(context)
2546 context.rounding = rounding
2548 return ans
2550 def max(self, other, context=None):
2551 """Returns the larger value.
2553 Like max(self, other) except if one is not a number, returns
2554 NaN (and signals if one is sNaN). Also rounds.
2556 other = _convert_other(other, raiseit=True)
2558 if context is None:
2559 context = getcontext()
2561 if self._is_special or other._is_special:
2562 # If one operand is a quiet NaN and the other is number, then the
2563 # number is always returned
2564 sn = self._isnan()
2565 on = other._isnan()
2566 if sn or on:
2567 if on == 1 and sn != 2:
2568 return self._fix_nan(context)
2569 if sn == 1 and on != 2:
2570 return other._fix_nan(context)
2571 return self._check_nans(other, context)
2573 c = self._cmp(other)
2574 if c == 0:
2575 # If both operands are finite and equal in numerical value
2576 # then an ordering is applied:
2578 # If the signs differ then max returns the operand with the
2579 # positive sign and min returns the operand with the negative sign
2581 # If the signs are the same then the exponent is used to select
2582 # the result. This is exactly the ordering used in compare_total.
2583 c = self.compare_total(other)
2585 if c == -1:
2586 ans = other
2587 else:
2588 ans = self
2590 return ans._fix(context)
2592 def min(self, other, context=None):
2593 """Returns the smaller value.
2595 Like min(self, other) except if one is not a number, returns
2596 NaN (and signals if one is sNaN). Also rounds.
2598 other = _convert_other(other, raiseit=True)
2600 if context is None:
2601 context = getcontext()
2603 if self._is_special or other._is_special:
2604 # If one operand is a quiet NaN and the other is number, then the
2605 # number is always returned
2606 sn = self._isnan()
2607 on = other._isnan()
2608 if sn or on:
2609 if on == 1 and sn != 2:
2610 return self._fix_nan(context)
2611 if sn == 1 and on != 2:
2612 return other._fix_nan(context)
2613 return self._check_nans(other, context)
2615 c = self._cmp(other)
2616 if c == 0:
2617 c = self.compare_total(other)
2619 if c == -1:
2620 ans = self
2621 else:
2622 ans = other
2624 return ans._fix(context)
2626 def _isinteger(self):
2627 """Returns whether self is an integer"""
2628 if self._is_special:
2629 return False
2630 if self._exp >= 0:
2631 return True
2632 rest = self._int[self._exp:]
2633 return rest == '0'*len(rest)
2635 def _iseven(self):
2636 """Returns True if self is even. Assumes self is an integer."""
2637 if not self or self._exp > 0:
2638 return True
2639 return self._int[-1+self._exp] in '02468'
2641 def adjusted(self):
2642 """Return the adjusted exponent of self"""
2643 try:
2644 return self._exp + len(self._int) - 1
2645 # If NaN or Infinity, self._exp is string
2646 except TypeError:
2647 return 0
2649 def canonical(self, context=None):
2650 """Returns the same Decimal object.
2652 As we do not have different encodings for the same number, the
2653 received object already is in its canonical form.
2655 return self
2657 def compare_signal(self, other, context=None):
2658 """Compares self to the other operand numerically.
2660 It's pretty much like compare(), but all NaNs signal, with signaling
2661 NaNs taking precedence over quiet NaNs.
2663 other = _convert_other(other, raiseit = True)
2664 ans = self._compare_check_nans(other, context)
2665 if ans:
2666 return ans
2667 return self.compare(other, context=context)
2669 def compare_total(self, other):
2670 """Compares self to other using the abstract representations.
2672 This is not like the standard compare, which use their numerical
2673 value. Note that a total ordering is defined for all possible abstract
2674 representations.
2676 # if one is negative and the other is positive, it's easy
2677 if self._sign and not other._sign:
2678 return Dec_n1
2679 if not self._sign and other._sign:
2680 return Dec_p1
2681 sign = self._sign
2683 # let's handle both NaN types
2684 self_nan = self._isnan()
2685 other_nan = other._isnan()
2686 if self_nan or other_nan:
2687 if self_nan == other_nan:
2688 if self._int < other._int:
2689 if sign:
2690 return Dec_p1
2691 else:
2692 return Dec_n1
2693 if self._int > other._int:
2694 if sign:
2695 return Dec_n1
2696 else:
2697 return Dec_p1
2698 return Dec_0
2700 if sign:
2701 if self_nan == 1:
2702 return Dec_n1
2703 if other_nan == 1:
2704 return Dec_p1
2705 if self_nan == 2:
2706 return Dec_n1
2707 if other_nan == 2:
2708 return Dec_p1
2709 else:
2710 if self_nan == 1:
2711 return Dec_p1
2712 if other_nan == 1:
2713 return Dec_n1
2714 if self_nan == 2:
2715 return Dec_p1
2716 if other_nan == 2:
2717 return Dec_n1
2719 if self < other:
2720 return Dec_n1
2721 if self > other:
2722 return Dec_p1
2724 if self._exp < other._exp:
2725 if sign:
2726 return Dec_p1
2727 else:
2728 return Dec_n1
2729 if self._exp > other._exp:
2730 if sign:
2731 return Dec_n1
2732 else:
2733 return Dec_p1
2734 return Dec_0
2737 def compare_total_mag(self, other):
2738 """Compares self to other using abstract repr., ignoring sign.
2740 Like compare_total, but with operand's sign ignored and assumed to be 0.
2742 s = self.copy_abs()
2743 o = other.copy_abs()
2744 return s.compare_total(o)
2746 def copy_abs(self):
2747 """Returns a copy with the sign set to 0. """
2748 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2750 def copy_negate(self):
2751 """Returns a copy with the sign inverted."""
2752 if self._sign:
2753 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2754 else:
2755 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2757 def copy_sign(self, other):
2758 """Returns self with the sign of other."""
2759 return _dec_from_triple(other._sign, self._int,
2760 self._exp, self._is_special)
2762 def exp(self, context=None):
2763 """Returns e ** self."""
2765 if context is None:
2766 context = getcontext()
2768 # exp(NaN) = NaN
2769 ans = self._check_nans(context=context)
2770 if ans:
2771 return ans
2773 # exp(-Infinity) = 0
2774 if self._isinfinity() == -1:
2775 return Dec_0
2777 # exp(0) = 1
2778 if not self:
2779 return Dec_p1
2781 # exp(Infinity) = Infinity
2782 if self._isinfinity() == 1:
2783 return Decimal(self)
2785 # the result is now guaranteed to be inexact (the true
2786 # mathematical result is transcendental). There's no need to
2787 # raise Rounded and Inexact here---they'll always be raised as
2788 # a result of the call to _fix.
2789 p = context.prec
2790 adj = self.adjusted()
2792 # we only need to do any computation for quite a small range
2793 # of adjusted exponents---for example, -29 <= adj <= 10 for
2794 # the default context. For smaller exponent the result is
2795 # indistinguishable from 1 at the given precision, while for
2796 # larger exponent the result either overflows or underflows.
2797 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2798 # overflow
2799 ans = _dec_from_triple(0, '1', context.Emax+1)
2800 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2801 # underflow to 0
2802 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2803 elif self._sign == 0 and adj < -p:
2804 # p+1 digits; final round will raise correct flags
2805 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2806 elif self._sign == 1 and adj < -p-1:
2807 # p+1 digits; final round will raise correct flags
2808 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2809 # general case
2810 else:
2811 op = _WorkRep(self)
2812 c, e = op.int, op.exp
2813 if op.sign == 1:
2814 c = -c
2816 # compute correctly rounded result: increase precision by
2817 # 3 digits at a time until we get an unambiguously
2818 # roundable result
2819 extra = 3
2820 while True:
2821 coeff, exp = _dexp(c, e, p+extra)
2822 if coeff % (5*10**(len(str(coeff))-p-1)):
2823 break
2824 extra += 3
2826 ans = _dec_from_triple(0, str(coeff), exp)
2828 # at this stage, ans should round correctly with *any*
2829 # rounding mode, not just with ROUND_HALF_EVEN
2830 context = context._shallow_copy()
2831 rounding = context._set_rounding(ROUND_HALF_EVEN)
2832 ans = ans._fix(context)
2833 context.rounding = rounding
2835 return ans
2837 def is_canonical(self):
2838 """Return True if self is canonical; otherwise return False.
2840 Currently, the encoding of a Decimal instance is always
2841 canonical, so this method returns True for any Decimal.
2843 return True
2845 def is_finite(self):
2846 """Return True if self is finite; otherwise return False.
2848 A Decimal instance is considered finite if it is neither
2849 infinite nor a NaN.
2851 return not self._is_special
2853 def is_infinite(self):
2854 """Return True if self is infinite; otherwise return False."""
2855 return self._exp == 'F'
2857 def is_nan(self):
2858 """Return True if self is a qNaN or sNaN; otherwise return False."""
2859 return self._exp in ('n', 'N')
2861 def is_normal(self, context=None):
2862 """Return True if self is a normal number; otherwise return False."""
2863 if self._is_special or not self:
2864 return False
2865 if context is None:
2866 context = getcontext()
2867 return context.Emin <= self.adjusted() <= context.Emax
2869 def is_qnan(self):
2870 """Return True if self is a quiet NaN; otherwise return False."""
2871 return self._exp == 'n'
2873 def is_signed(self):
2874 """Return True if self is negative; otherwise return False."""
2875 return self._sign == 1
2877 def is_snan(self):
2878 """Return True if self is a signaling NaN; otherwise return False."""
2879 return self._exp == 'N'
2881 def is_subnormal(self, context=None):
2882 """Return True if self is subnormal; otherwise return False."""
2883 if self._is_special or not self:
2884 return False
2885 if context is None:
2886 context = getcontext()
2887 return self.adjusted() < context.Emin
2889 def is_zero(self):
2890 """Return True if self is a zero; otherwise return False."""
2891 return not self._is_special and self._int == '0'
2893 def _ln_exp_bound(self):
2894 """Compute a lower bound for the adjusted exponent of self.ln().
2895 In other words, compute r such that self.ln() >= 10**r. Assumes
2896 that self is finite and positive and that self != 1.
2899 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2900 adj = self._exp + len(self._int) - 1
2901 if adj >= 1:
2902 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2903 return len(str(adj*23//10)) - 1
2904 if adj <= -2:
2905 # argument <= 0.1
2906 return len(str((-1-adj)*23//10)) - 1
2907 op = _WorkRep(self)
2908 c, e = op.int, op.exp
2909 if adj == 0:
2910 # 1 < self < 10
2911 num = str(c-10**-e)
2912 den = str(c)
2913 return len(num) - len(den) - (num < den)
2914 # adj == -1, 0.1 <= self < 1
2915 return e + len(str(10**-e - c)) - 1
2918 def ln(self, context=None):
2919 """Returns the natural (base e) logarithm of self."""
2921 if context is None:
2922 context = getcontext()
2924 # ln(NaN) = NaN
2925 ans = self._check_nans(context=context)
2926 if ans:
2927 return ans
2929 # ln(0.0) == -Infinity
2930 if not self:
2931 return negInf
2933 # ln(Infinity) = Infinity
2934 if self._isinfinity() == 1:
2935 return Inf
2937 # ln(1.0) == 0.0
2938 if self == Dec_p1:
2939 return Dec_0
2941 # ln(negative) raises InvalidOperation
2942 if self._sign == 1:
2943 return context._raise_error(InvalidOperation,
2944 'ln of a negative value')
2946 # result is irrational, so necessarily inexact
2947 op = _WorkRep(self)
2948 c, e = op.int, op.exp
2949 p = context.prec
2951 # correctly rounded result: repeatedly increase precision by 3
2952 # until we get an unambiguously roundable result
2953 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2954 while True:
2955 coeff = _dlog(c, e, places)
2956 # assert len(str(abs(coeff)))-p >= 1
2957 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2958 break
2959 places += 3
2960 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2962 context = context._shallow_copy()
2963 rounding = context._set_rounding(ROUND_HALF_EVEN)
2964 ans = ans._fix(context)
2965 context.rounding = rounding
2966 return ans
2968 def _log10_exp_bound(self):
2969 """Compute a lower bound for the adjusted exponent of self.log10().
2970 In other words, find r such that self.log10() >= 10**r.
2971 Assumes that self is finite and positive and that self != 1.
2974 # For x >= 10 or x < 0.1 we only need a bound on the integer
2975 # part of log10(self), and this comes directly from the
2976 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2977 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2978 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2980 adj = self._exp + len(self._int) - 1
2981 if adj >= 1:
2982 # self >= 10
2983 return len(str(adj))-1
2984 if adj <= -2:
2985 # self < 0.1
2986 return len(str(-1-adj))-1
2987 op = _WorkRep(self)
2988 c, e = op.int, op.exp
2989 if adj == 0:
2990 # 1 < self < 10
2991 num = str(c-10**-e)
2992 den = str(231*c)
2993 return len(num) - len(den) - (num < den) + 2
2994 # adj == -1, 0.1 <= self < 1
2995 num = str(10**-e-c)
2996 return len(num) + e - (num < "231") - 1
2998 def log10(self, context=None):
2999 """Returns the base 10 logarithm of self."""
3001 if context is None:
3002 context = getcontext()
3004 # log10(NaN) = NaN
3005 ans = self._check_nans(context=context)
3006 if ans:
3007 return ans
3009 # log10(0.0) == -Infinity
3010 if not self:
3011 return negInf
3013 # log10(Infinity) = Infinity
3014 if self._isinfinity() == 1:
3015 return Inf
3017 # log10(negative or -Infinity) raises InvalidOperation
3018 if self._sign == 1:
3019 return context._raise_error(InvalidOperation,
3020 'log10 of a negative value')
3022 # log10(10**n) = n
3023 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3024 # answer may need rounding
3025 ans = Decimal(self._exp + len(self._int) - 1)
3026 else:
3027 # result is irrational, so necessarily inexact
3028 op = _WorkRep(self)
3029 c, e = op.int, op.exp
3030 p = context.prec
3032 # correctly rounded result: repeatedly increase precision
3033 # until result is unambiguously roundable
3034 places = p-self._log10_exp_bound()+2
3035 while True:
3036 coeff = _dlog10(c, e, places)
3037 # assert len(str(abs(coeff)))-p >= 1
3038 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3039 break
3040 places += 3
3041 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3043 context = context._shallow_copy()
3044 rounding = context._set_rounding(ROUND_HALF_EVEN)
3045 ans = ans._fix(context)
3046 context.rounding = rounding
3047 return ans
3049 def logb(self, context=None):
3050 """ Returns the exponent of the magnitude of self's MSD.
3052 The result is the integer which is the exponent of the magnitude
3053 of the most significant digit of self (as though it were truncated
3054 to a single digit while maintaining the value of that digit and
3055 without limiting the resulting exponent).
3057 # logb(NaN) = NaN
3058 ans = self._check_nans(context=context)
3059 if ans:
3060 return ans
3062 if context is None:
3063 context = getcontext()
3065 # logb(+/-Inf) = +Inf
3066 if self._isinfinity():
3067 return Inf
3069 # logb(0) = -Inf, DivisionByZero
3070 if not self:
3071 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3073 # otherwise, simply return the adjusted exponent of self, as a
3074 # Decimal. Note that no attempt is made to fit the result
3075 # into the current context.
3076 return Decimal(self.adjusted())
3078 def _islogical(self):
3079 """Return True if self is a logical operand.
3081 For being logical, it must be a finite number with a sign of 0,
3082 an exponent of 0, and a coefficient whose digits must all be
3083 either 0 or 1.
3085 if self._sign != 0 or self._exp != 0:
3086 return False
3087 for dig in self._int:
3088 if dig not in '01':
3089 return False
3090 return True
3092 def _fill_logical(self, context, opa, opb):
3093 dif = context.prec - len(opa)
3094 if dif > 0:
3095 opa = '0'*dif + opa
3096 elif dif < 0:
3097 opa = opa[-context.prec:]
3098 dif = context.prec - len(opb)
3099 if dif > 0:
3100 opb = '0'*dif + opb
3101 elif dif < 0:
3102 opb = opb[-context.prec:]
3103 return opa, opb
3105 def logical_and(self, other, context=None):
3106 """Applies an 'and' operation between self and other's digits."""
3107 if context is None:
3108 context = getcontext()
3109 if not self._islogical() or not other._islogical():
3110 return context._raise_error(InvalidOperation)
3112 # fill to context.prec
3113 (opa, opb) = self._fill_logical(context, self._int, other._int)
3115 # make the operation, and clean starting zeroes
3116 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3117 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3119 def logical_invert(self, context=None):
3120 """Invert all its digits."""
3121 if context is None:
3122 context = getcontext()
3123 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3124 context)
3126 def logical_or(self, other, context=None):
3127 """Applies an 'or' operation between self and other's digits."""
3128 if context is None:
3129 context = getcontext()
3130 if not self._islogical() or not other._islogical():
3131 return context._raise_error(InvalidOperation)
3133 # fill to context.prec
3134 (opa, opb) = self._fill_logical(context, self._int, other._int)
3136 # make the operation, and clean starting zeroes
3137 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3138 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3140 def logical_xor(self, other, context=None):
3141 """Applies an 'xor' operation between self and other's digits."""
3142 if context is None:
3143 context = getcontext()
3144 if not self._islogical() or not other._islogical():
3145 return context._raise_error(InvalidOperation)
3147 # fill to context.prec
3148 (opa, opb) = self._fill_logical(context, self._int, other._int)
3150 # make the operation, and clean starting zeroes
3151 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3152 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3154 def max_mag(self, other, context=None):
3155 """Compares the values numerically with their sign ignored."""
3156 other = _convert_other(other, raiseit=True)
3158 if context is None:
3159 context = getcontext()
3161 if self._is_special or other._is_special:
3162 # If one operand is a quiet NaN and the other is number, then the
3163 # number is always returned
3164 sn = self._isnan()
3165 on = other._isnan()
3166 if sn or on:
3167 if on == 1 and sn != 2:
3168 return self._fix_nan(context)
3169 if sn == 1 and on != 2:
3170 return other._fix_nan(context)
3171 return self._check_nans(other, context)
3173 c = self.copy_abs()._cmp(other.copy_abs())
3174 if c == 0:
3175 c = self.compare_total(other)
3177 if c == -1:
3178 ans = other
3179 else:
3180 ans = self
3182 return ans._fix(context)
3184 def min_mag(self, other, context=None):
3185 """Compares the values numerically with their sign ignored."""
3186 other = _convert_other(other, raiseit=True)
3188 if context is None:
3189 context = getcontext()
3191 if self._is_special or other._is_special:
3192 # If one operand is a quiet NaN and the other is number, then the
3193 # number is always returned
3194 sn = self._isnan()
3195 on = other._isnan()
3196 if sn or on:
3197 if on == 1 and sn != 2:
3198 return self._fix_nan(context)
3199 if sn == 1 and on != 2:
3200 return other._fix_nan(context)
3201 return self._check_nans(other, context)
3203 c = self.copy_abs()._cmp(other.copy_abs())
3204 if c == 0:
3205 c = self.compare_total(other)
3207 if c == -1:
3208 ans = self
3209 else:
3210 ans = other
3212 return ans._fix(context)
3214 def next_minus(self, context=None):
3215 """Returns the largest representable number smaller than itself."""
3216 if context is None:
3217 context = getcontext()
3219 ans = self._check_nans(context=context)
3220 if ans:
3221 return ans
3223 if self._isinfinity() == -1:
3224 return negInf
3225 if self._isinfinity() == 1:
3226 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3228 context = context.copy()
3229 context._set_rounding(ROUND_FLOOR)
3230 context._ignore_all_flags()
3231 new_self = self._fix(context)
3232 if new_self != self:
3233 return new_self
3234 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3235 context)
3237 def next_plus(self, context=None):
3238 """Returns the smallest representable number larger than itself."""
3239 if context is None:
3240 context = getcontext()
3242 ans = self._check_nans(context=context)
3243 if ans:
3244 return ans
3246 if self._isinfinity() == 1:
3247 return Inf
3248 if self._isinfinity() == -1:
3249 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3251 context = context.copy()
3252 context._set_rounding(ROUND_CEILING)
3253 context._ignore_all_flags()
3254 new_self = self._fix(context)
3255 if new_self != self:
3256 return new_self
3257 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3258 context)
3260 def next_toward(self, other, context=None):
3261 """Returns the number closest to self, in the direction towards other.
3263 The result is the closest representable number to self
3264 (excluding self) that is in the direction towards other,
3265 unless both have the same value. If the two operands are
3266 numerically equal, then the result is a copy of self with the
3267 sign set to be the same as the sign of other.
3269 other = _convert_other(other, raiseit=True)
3271 if context is None:
3272 context = getcontext()
3274 ans = self._check_nans(other, context)
3275 if ans:
3276 return ans
3278 comparison = self._cmp(other)
3279 if comparison == 0:
3280 return self.copy_sign(other)
3282 if comparison == -1:
3283 ans = self.next_plus(context)
3284 else: # comparison == 1
3285 ans = self.next_minus(context)
3287 # decide which flags to raise using value of ans
3288 if ans._isinfinity():
3289 context._raise_error(Overflow,
3290 'Infinite result from next_toward',
3291 ans._sign)
3292 context._raise_error(Rounded)
3293 context._raise_error(Inexact)
3294 elif ans.adjusted() < context.Emin:
3295 context._raise_error(Underflow)
3296 context._raise_error(Subnormal)
3297 context._raise_error(Rounded)
3298 context._raise_error(Inexact)
3299 # if precision == 1 then we don't raise Clamped for a
3300 # result 0E-Etiny.
3301 if not ans:
3302 context._raise_error(Clamped)
3304 return ans
3306 def number_class(self, context=None):
3307 """Returns an indication of the class of self.
3309 The class is one of the following strings:
3310 sNaN
3312 -Infinity
3313 -Normal
3314 -Subnormal
3315 -Zero
3316 +Zero
3317 +Subnormal
3318 +Normal
3319 +Infinity
3321 if self.is_snan():
3322 return "sNaN"
3323 if self.is_qnan():
3324 return "NaN"
3325 inf = self._isinfinity()
3326 if inf == 1:
3327 return "+Infinity"
3328 if inf == -1:
3329 return "-Infinity"
3330 if self.is_zero():
3331 if self._sign:
3332 return "-Zero"
3333 else:
3334 return "+Zero"
3335 if context is None:
3336 context = getcontext()
3337 if self.is_subnormal(context=context):
3338 if self._sign:
3339 return "-Subnormal"
3340 else:
3341 return "+Subnormal"
3342 # just a normal, regular, boring number, :)
3343 if self._sign:
3344 return "-Normal"
3345 else:
3346 return "+Normal"
3348 def radix(self):
3349 """Just returns 10, as this is Decimal, :)"""
3350 return Decimal(10)
3352 def rotate(self, other, context=None):
3353 """Returns a rotated copy of self, value-of-other times."""
3354 if context is None:
3355 context = getcontext()
3357 ans = self._check_nans(other, context)
3358 if ans:
3359 return ans
3361 if other._exp != 0:
3362 return context._raise_error(InvalidOperation)
3363 if not (-context.prec <= int(other) <= context.prec):
3364 return context._raise_error(InvalidOperation)
3366 if self._isinfinity():
3367 return Decimal(self)
3369 # get values, pad if necessary
3370 torot = int(other)
3371 rotdig = self._int
3372 topad = context.prec - len(rotdig)
3373 if topad:
3374 rotdig = '0'*topad + rotdig
3376 # let's rotate!
3377 rotated = rotdig[torot:] + rotdig[:torot]
3378 return _dec_from_triple(self._sign,
3379 rotated.lstrip('0') or '0', self._exp)
3381 def scaleb (self, other, context=None):
3382 """Returns self operand after adding the second value to its exp."""
3383 if context is None:
3384 context = getcontext()
3386 ans = self._check_nans(other, context)
3387 if ans:
3388 return ans
3390 if other._exp != 0:
3391 return context._raise_error(InvalidOperation)
3392 liminf = -2 * (context.Emax + context.prec)
3393 limsup = 2 * (context.Emax + context.prec)
3394 if not (liminf <= int(other) <= limsup):
3395 return context._raise_error(InvalidOperation)
3397 if self._isinfinity():
3398 return Decimal(self)
3400 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3401 d = d._fix(context)
3402 return d
3404 def shift(self, other, context=None):
3405 """Returns a shifted copy of self, value-of-other times."""
3406 if context is None:
3407 context = getcontext()
3409 ans = self._check_nans(other, context)
3410 if ans:
3411 return ans
3413 if other._exp != 0:
3414 return context._raise_error(InvalidOperation)
3415 if not (-context.prec <= int(other) <= context.prec):
3416 return context._raise_error(InvalidOperation)
3418 if self._isinfinity():
3419 return Decimal(self)
3421 # get values, pad if necessary
3422 torot = int(other)
3423 if not torot:
3424 return Decimal(self)
3425 rotdig = self._int
3426 topad = context.prec - len(rotdig)
3427 if topad:
3428 rotdig = '0'*topad + rotdig
3430 # let's shift!
3431 if torot < 0:
3432 rotated = rotdig[:torot]
3433 else:
3434 rotated = rotdig + '0'*torot
3435 rotated = rotated[-context.prec:]
3437 return _dec_from_triple(self._sign,
3438 rotated.lstrip('0') or '0', self._exp)
3440 # Support for pickling, copy, and deepcopy
3441 def __reduce__(self):
3442 return (self.__class__, (str(self),))
3444 def __copy__(self):
3445 if type(self) == Decimal:
3446 return self # I'm immutable; therefore I am my own clone
3447 return self.__class__(str(self))
3449 def __deepcopy__(self, memo):
3450 if type(self) == Decimal:
3451 return self # My components are also immutable
3452 return self.__class__(str(self))
3454 # PEP 3101 support. See also _parse_format_specifier and _format_align
3455 def __format__(self, specifier, context=None):
3456 """Format a Decimal instance according to the given specifier.
3458 The specifier should be a standard format specifier, with the
3459 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3460 'F', 'g', 'G', and '%' are supported. If the formatting type
3461 is omitted it defaults to 'g' or 'G', depending on the value
3462 of context.capitals.
3464 At this time the 'n' format specifier type (which is supposed
3465 to use the current locale) is not supported.
3468 # Note: PEP 3101 says that if the type is not present then
3469 # there should be at least one digit after the decimal point.
3470 # We take the liberty of ignoring this requirement for
3471 # Decimal---it's presumably there to make sure that
3472 # format(float, '') behaves similarly to str(float).
3473 if context is None:
3474 context = getcontext()
3476 spec = _parse_format_specifier(specifier)
3478 # special values don't care about the type or precision...
3479 if self._is_special:
3480 return _format_align(str(self), spec)
3482 # a type of None defaults to 'g' or 'G', depending on context
3483 # if type is '%', adjust exponent of self accordingly
3484 if spec['type'] is None:
3485 spec['type'] = ['g', 'G'][context.capitals]
3486 elif spec['type'] == '%':
3487 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3489 # round if necessary, taking rounding mode from the context
3490 rounding = context.rounding
3491 precision = spec['precision']
3492 if precision is not None:
3493 if spec['type'] in 'eE':
3494 self = self._round(precision+1, rounding)
3495 elif spec['type'] in 'gG':
3496 if len(self._int) > precision:
3497 self = self._round(precision, rounding)
3498 elif spec['type'] in 'fF%':
3499 self = self._rescale(-precision, rounding)
3500 # special case: zeros with a positive exponent can't be
3501 # represented in fixed point; rescale them to 0e0.
3502 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3503 self = self._rescale(0, rounding)
3505 # figure out placement of the decimal point
3506 leftdigits = self._exp + len(self._int)
3507 if spec['type'] in 'fF%':
3508 dotplace = leftdigits
3509 elif spec['type'] in 'eE':
3510 if not self and precision is not None:
3511 dotplace = 1 - precision
3512 else:
3513 dotplace = 1
3514 elif spec['type'] in 'gG':
3515 if self._exp <= 0 and leftdigits > -6:
3516 dotplace = leftdigits
3517 else:
3518 dotplace = 1
3520 # figure out main part of numeric string...
3521 if dotplace <= 0:
3522 num = '0.' + '0'*(-dotplace) + self._int
3523 elif dotplace >= len(self._int):
3524 # make sure we're not padding a '0' with extra zeros on the right
3525 assert dotplace==len(self._int) or self._int != '0'
3526 num = self._int + '0'*(dotplace-len(self._int))
3527 else:
3528 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3530 # ...then the trailing exponent, or trailing '%'
3531 if leftdigits != dotplace or spec['type'] in 'eE':
3532 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3533 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3534 elif spec['type'] == '%':
3535 num = num + '%'
3537 # add sign
3538 if self._sign == 1:
3539 num = '-' + num
3540 return _format_align(num, spec)
3543 def _dec_from_triple(sign, coefficient, exponent, special=False):
3544 """Create a decimal instance directly, without any validation,
3545 normalization (e.g. removal of leading zeros) or argument
3546 conversion.
3548 This function is for *internal use only*.
3551 self = object.__new__(Decimal)
3552 self._sign = sign
3553 self._int = coefficient
3554 self._exp = exponent
3555 self._is_special = special
3557 return self
3559 ##### Context class #######################################################
3562 # get rounding method function:
3563 rounding_functions = [name for name in Decimal.__dict__.keys()
3564 if name.startswith('_round_')]
3565 for name in rounding_functions:
3566 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3567 globalname = name[1:].upper()
3568 val = globals()[globalname]
3569 Decimal._pick_rounding_function[val] = name
3571 del name, val, globalname, rounding_functions
3573 class _ContextManager(object):
3574 """Context manager class to support localcontext().
3576 Sets a copy of the supplied context in __enter__() and restores
3577 the previous decimal context in __exit__()
3579 def __init__(self, new_context):
3580 self.new_context = new_context.copy()
3581 def __enter__(self):
3582 self.saved_context = getcontext()
3583 setcontext(self.new_context)
3584 return self.new_context
3585 def __exit__(self, t, v, tb):
3586 setcontext(self.saved_context)
3588 class Context(object):
3589 """Contains the context for a Decimal instance.
3591 Contains:
3592 prec - precision (for use in rounding, division, square roots..)
3593 rounding - rounding type (how you round)
3594 traps - If traps[exception] = 1, then the exception is
3595 raised when it is caused. Otherwise, a value is
3596 substituted in.
3597 flags - When an exception is caused, flags[exception] is set.
3598 (Whether or not the trap_enabler is set)
3599 Should be reset by user of Decimal instance.
3600 Emin - Minimum exponent
3601 Emax - Maximum exponent
3602 capitals - If 1, 1*10^1 is printed as 1E+1.
3603 If 0, printed as 1e1
3604 _clamp - If 1, change exponents if too high (Default 0)
3607 def __init__(self, prec=None, rounding=None,
3608 traps=None, flags=None,
3609 Emin=None, Emax=None,
3610 capitals=None, _clamp=0,
3611 _ignored_flags=None):
3612 if flags is None:
3613 flags = []
3614 if _ignored_flags is None:
3615 _ignored_flags = []
3616 if not isinstance(flags, dict):
3617 flags = dict([(s, int(s in flags)) for s in _signals])
3618 if traps is not None and not isinstance(traps, dict):
3619 traps = dict([(s, int(s in traps)) for s in _signals])
3620 for name, val in locals().items():
3621 if val is None:
3622 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3623 else:
3624 setattr(self, name, val)
3625 del self.self
3627 def __repr__(self):
3628 """Show the current context."""
3629 s = []
3630 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3631 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3632 % vars(self))
3633 names = [f.__name__ for f, v in self.flags.items() if v]
3634 s.append('flags=[' + ', '.join(names) + ']')
3635 names = [t.__name__ for t, v in self.traps.items() if v]
3636 s.append('traps=[' + ', '.join(names) + ']')
3637 return ', '.join(s) + ')'
3639 def clear_flags(self):
3640 """Reset all flags to zero"""
3641 for flag in self.flags:
3642 self.flags[flag] = 0
3644 def _shallow_copy(self):
3645 """Returns a shallow copy from self."""
3646 nc = Context(self.prec, self.rounding, self.traps,
3647 self.flags, self.Emin, self.Emax,
3648 self.capitals, self._clamp, self._ignored_flags)
3649 return nc
3651 def copy(self):
3652 """Returns a deep copy from self."""
3653 nc = Context(self.prec, self.rounding, self.traps.copy(),
3654 self.flags.copy(), self.Emin, self.Emax,
3655 self.capitals, self._clamp, self._ignored_flags)
3656 return nc
3657 __copy__ = copy
3659 def _raise_error(self, condition, explanation = None, *args):
3660 """Handles an error
3662 If the flag is in _ignored_flags, returns the default response.
3663 Otherwise, it sets the flag, then, if the corresponding
3664 trap_enabler is set, it reaises the exception. Otherwise, it returns
3665 the default value after setting the flag.
3667 error = _condition_map.get(condition, condition)
3668 if error in self._ignored_flags:
3669 # Don't touch the flag
3670 return error().handle(self, *args)
3672 self.flags[error] = 1
3673 if not self.traps[error]:
3674 # The errors define how to handle themselves.
3675 return condition().handle(self, *args)
3677 # Errors should only be risked on copies of the context
3678 # self._ignored_flags = []
3679 raise error(explanation)
3681 def _ignore_all_flags(self):
3682 """Ignore all flags, if they are raised"""
3683 return self._ignore_flags(*_signals)
3685 def _ignore_flags(self, *flags):
3686 """Ignore the flags, if they are raised"""
3687 # Do not mutate-- This way, copies of a context leave the original
3688 # alone.
3689 self._ignored_flags = (self._ignored_flags + list(flags))
3690 return list(flags)
3692 def _regard_flags(self, *flags):
3693 """Stop ignoring the flags, if they are raised"""
3694 if flags and isinstance(flags[0], (tuple,list)):
3695 flags = flags[0]
3696 for flag in flags:
3697 self._ignored_flags.remove(flag)
3699 def __hash__(self):
3700 """A Context cannot be hashed."""
3701 # We inherit object.__hash__, so we must deny this explicitly
3702 raise TypeError("Cannot hash a Context.")
3704 def Etiny(self):
3705 """Returns Etiny (= Emin - prec + 1)"""
3706 return int(self.Emin - self.prec + 1)
3708 def Etop(self):
3709 """Returns maximum exponent (= Emax - prec + 1)"""
3710 return int(self.Emax - self.prec + 1)
3712 def _set_rounding(self, type):
3713 """Sets the rounding type.
3715 Sets the rounding type, and returns the current (previous)
3716 rounding type. Often used like:
3718 context = context.copy()
3719 # so you don't change the calling context
3720 # if an error occurs in the middle.
3721 rounding = context._set_rounding(ROUND_UP)
3722 val = self.__sub__(other, context=context)
3723 context._set_rounding(rounding)
3725 This will make it round up for that operation.
3727 rounding = self.rounding
3728 self.rounding= type
3729 return rounding
3731 def create_decimal(self, num='0'):
3732 """Creates a new Decimal instance but using self as context.
3734 This method implements the to-number operation of the
3735 IBM Decimal specification."""
3737 if isinstance(num, str) and num != num.strip():
3738 return self._raise_error(ConversionSyntax,
3739 "no trailing or leading whitespace is "
3740 "permitted.")
3742 d = Decimal(num, context=self)
3743 if d._isnan() and len(d._int) > self.prec - self._clamp:
3744 return self._raise_error(ConversionSyntax,
3745 "diagnostic info too long in NaN")
3746 return d._fix(self)
3748 # Methods
3749 def abs(self, a):
3750 """Returns the absolute value of the operand.
3752 If the operand is negative, the result is the same as using the minus
3753 operation on the operand. Otherwise, the result is the same as using
3754 the plus operation on the operand.
3756 >>> ExtendedContext.abs(Decimal('2.1'))
3757 Decimal('2.1')
3758 >>> ExtendedContext.abs(Decimal('-100'))
3759 Decimal('100')
3760 >>> ExtendedContext.abs(Decimal('101.5'))
3761 Decimal('101.5')
3762 >>> ExtendedContext.abs(Decimal('-101.5'))
3763 Decimal('101.5')
3765 return a.__abs__(context=self)
3767 def add(self, a, b):
3768 """Return the sum of the two operands.
3770 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3771 Decimal('19.00')
3772 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3773 Decimal('1.02E+4')
3775 return a.__add__(b, context=self)
3777 def _apply(self, a):
3778 return str(a._fix(self))
3780 def canonical(self, a):
3781 """Returns the same Decimal object.
3783 As we do not have different encodings for the same number, the
3784 received object already is in its canonical form.
3786 >>> ExtendedContext.canonical(Decimal('2.50'))
3787 Decimal('2.50')
3789 return a.canonical(context=self)
3791 def compare(self, a, b):
3792 """Compares values numerically.
3794 If the signs of the operands differ, a value representing each operand
3795 ('-1' if the operand is less than zero, '0' if the operand is zero or
3796 negative zero, or '1' if the operand is greater than zero) is used in
3797 place of that operand for the comparison instead of the actual
3798 operand.
3800 The comparison is then effected by subtracting the second operand from
3801 the first and then returning a value according to the result of the
3802 subtraction: '-1' if the result is less than zero, '0' if the result is
3803 zero or negative zero, or '1' if the result is greater than zero.
3805 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3806 Decimal('-1')
3807 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3808 Decimal('0')
3809 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3810 Decimal('0')
3811 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3812 Decimal('1')
3813 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3814 Decimal('1')
3815 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3816 Decimal('-1')
3818 return a.compare(b, context=self)
3820 def compare_signal(self, a, b):
3821 """Compares the values of the two operands numerically.
3823 It's pretty much like compare(), but all NaNs signal, with signaling
3824 NaNs taking precedence over quiet NaNs.
3826 >>> c = ExtendedContext
3827 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3828 Decimal('-1')
3829 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3830 Decimal('0')
3831 >>> c.flags[InvalidOperation] = 0
3832 >>> print(c.flags[InvalidOperation])
3834 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3835 Decimal('NaN')
3836 >>> print(c.flags[InvalidOperation])
3838 >>> c.flags[InvalidOperation] = 0
3839 >>> print(c.flags[InvalidOperation])
3841 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3842 Decimal('NaN')
3843 >>> print(c.flags[InvalidOperation])
3846 return a.compare_signal(b, context=self)
3848 def compare_total(self, a, b):
3849 """Compares two operands using their abstract representation.
3851 This is not like the standard compare, which use their numerical
3852 value. Note that a total ordering is defined for all possible abstract
3853 representations.
3855 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3856 Decimal('-1')
3857 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3858 Decimal('-1')
3859 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3860 Decimal('-1')
3861 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3862 Decimal('0')
3863 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3864 Decimal('1')
3865 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3866 Decimal('-1')
3868 return a.compare_total(b)
3870 def compare_total_mag(self, a, b):
3871 """Compares two operands using their abstract representation ignoring sign.
3873 Like compare_total, but with operand's sign ignored and assumed to be 0.
3875 return a.compare_total_mag(b)
3877 def copy_abs(self, a):
3878 """Returns a copy of the operand with the sign set to 0.
3880 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3881 Decimal('2.1')
3882 >>> ExtendedContext.copy_abs(Decimal('-100'))
3883 Decimal('100')
3885 return a.copy_abs()
3887 def copy_decimal(self, a):
3888 """Returns a copy of the decimal objet.
3890 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3891 Decimal('2.1')
3892 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3893 Decimal('-1.00')
3895 return Decimal(a)
3897 def copy_negate(self, a):
3898 """Returns a copy of the operand with the sign inverted.
3900 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3901 Decimal('-101.5')
3902 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3903 Decimal('101.5')
3905 return a.copy_negate()
3907 def copy_sign(self, a, b):
3908 """Copies the second operand's sign to the first one.
3910 In detail, it returns a copy of the first operand with the sign
3911 equal to the sign of the second operand.
3913 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3914 Decimal('1.50')
3915 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3916 Decimal('1.50')
3917 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3918 Decimal('-1.50')
3919 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3920 Decimal('-1.50')
3922 return a.copy_sign(b)
3924 def divide(self, a, b):
3925 """Decimal division in a specified context.
3927 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3928 Decimal('0.333333333')
3929 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3930 Decimal('0.666666667')
3931 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3932 Decimal('2.5')
3933 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3934 Decimal('0.1')
3935 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3936 Decimal('1')
3937 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3938 Decimal('4.00')
3939 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3940 Decimal('1.20')
3941 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3942 Decimal('10')
3943 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3944 Decimal('1000')
3945 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3946 Decimal('1.20E+6')
3948 return a.__truediv__(b, context=self)
3950 def divide_int(self, a, b):
3951 """Divides two numbers and returns the integer part of the result.
3953 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3954 Decimal('0')
3955 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3956 Decimal('3')
3957 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3958 Decimal('3')
3960 return a.__floordiv__(b, context=self)
3962 def divmod(self, a, b):
3963 return a.__divmod__(b, context=self)
3965 def exp(self, a):
3966 """Returns e ** a.
3968 >>> c = ExtendedContext.copy()
3969 >>> c.Emin = -999
3970 >>> c.Emax = 999
3971 >>> c.exp(Decimal('-Infinity'))
3972 Decimal('0')
3973 >>> c.exp(Decimal('-1'))
3974 Decimal('0.367879441')
3975 >>> c.exp(Decimal('0'))
3976 Decimal('1')
3977 >>> c.exp(Decimal('1'))
3978 Decimal('2.71828183')
3979 >>> c.exp(Decimal('0.693147181'))
3980 Decimal('2.00000000')
3981 >>> c.exp(Decimal('+Infinity'))
3982 Decimal('Infinity')
3984 return a.exp(context=self)
3986 def fma(self, a, b, c):
3987 """Returns a multiplied by b, plus c.
3989 The first two operands are multiplied together, using multiply,
3990 the third operand is then added to the result of that
3991 multiplication, using add, all with only one final rounding.
3993 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3994 Decimal('22')
3995 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3996 Decimal('-8')
3997 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3998 Decimal('1.38435736E+12')
4000 return a.fma(b, c, context=self)
4002 def is_canonical(self, a):
4003 """Return True if the operand is canonical; otherwise return False.
4005 Currently, the encoding of a Decimal instance is always
4006 canonical, so this method returns True for any Decimal.
4008 >>> ExtendedContext.is_canonical(Decimal('2.50'))
4009 True
4011 return a.is_canonical()
4013 def is_finite(self, a):
4014 """Return True if the operand is finite; otherwise return False.
4016 A Decimal instance is considered finite if it is neither
4017 infinite nor a NaN.
4019 >>> ExtendedContext.is_finite(Decimal('2.50'))
4020 True
4021 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4022 True
4023 >>> ExtendedContext.is_finite(Decimal('0'))
4024 True
4025 >>> ExtendedContext.is_finite(Decimal('Inf'))
4026 False
4027 >>> ExtendedContext.is_finite(Decimal('NaN'))
4028 False
4030 return a.is_finite()
4032 def is_infinite(self, a):
4033 """Return True if the operand is infinite; otherwise return False.
4035 >>> ExtendedContext.is_infinite(Decimal('2.50'))
4036 False
4037 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4038 True
4039 >>> ExtendedContext.is_infinite(Decimal('NaN'))
4040 False
4042 return a.is_infinite()
4044 def is_nan(self, a):
4045 """Return True if the operand is a qNaN or sNaN;
4046 otherwise return False.
4048 >>> ExtendedContext.is_nan(Decimal('2.50'))
4049 False
4050 >>> ExtendedContext.is_nan(Decimal('NaN'))
4051 True
4052 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4053 True
4055 return a.is_nan()
4057 def is_normal(self, a):
4058 """Return True if the operand is a normal number;
4059 otherwise return False.
4061 >>> c = ExtendedContext.copy()
4062 >>> c.Emin = -999
4063 >>> c.Emax = 999
4064 >>> c.is_normal(Decimal('2.50'))
4065 True
4066 >>> c.is_normal(Decimal('0.1E-999'))
4067 False
4068 >>> c.is_normal(Decimal('0.00'))
4069 False
4070 >>> c.is_normal(Decimal('-Inf'))
4071 False
4072 >>> c.is_normal(Decimal('NaN'))
4073 False
4075 return a.is_normal(context=self)
4077 def is_qnan(self, a):
4078 """Return True if the operand is a quiet NaN; otherwise return False.
4080 >>> ExtendedContext.is_qnan(Decimal('2.50'))
4081 False
4082 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4083 True
4084 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4085 False
4087 return a.is_qnan()
4089 def is_signed(self, a):
4090 """Return True if the operand is negative; otherwise return False.
4092 >>> ExtendedContext.is_signed(Decimal('2.50'))
4093 False
4094 >>> ExtendedContext.is_signed(Decimal('-12'))
4095 True
4096 >>> ExtendedContext.is_signed(Decimal('-0'))
4097 True
4099 return a.is_signed()
4101 def is_snan(self, a):
4102 """Return True if the operand is a signaling NaN;
4103 otherwise return False.
4105 >>> ExtendedContext.is_snan(Decimal('2.50'))
4106 False
4107 >>> ExtendedContext.is_snan(Decimal('NaN'))
4108 False
4109 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4110 True
4112 return a.is_snan()
4114 def is_subnormal(self, a):
4115 """Return True if the operand is subnormal; otherwise return False.
4117 >>> c = ExtendedContext.copy()
4118 >>> c.Emin = -999
4119 >>> c.Emax = 999
4120 >>> c.is_subnormal(Decimal('2.50'))
4121 False
4122 >>> c.is_subnormal(Decimal('0.1E-999'))
4123 True
4124 >>> c.is_subnormal(Decimal('0.00'))
4125 False
4126 >>> c.is_subnormal(Decimal('-Inf'))
4127 False
4128 >>> c.is_subnormal(Decimal('NaN'))
4129 False
4131 return a.is_subnormal(context=self)
4133 def is_zero(self, a):
4134 """Return True if the operand is a zero; otherwise return False.
4136 >>> ExtendedContext.is_zero(Decimal('0'))
4137 True
4138 >>> ExtendedContext.is_zero(Decimal('2.50'))
4139 False
4140 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4141 True
4143 return a.is_zero()
4145 def ln(self, a):
4146 """Returns the natural (base e) logarithm of the operand.
4148 >>> c = ExtendedContext.copy()
4149 >>> c.Emin = -999
4150 >>> c.Emax = 999
4151 >>> c.ln(Decimal('0'))
4152 Decimal('-Infinity')
4153 >>> c.ln(Decimal('1.000'))
4154 Decimal('0')
4155 >>> c.ln(Decimal('2.71828183'))
4156 Decimal('1.00000000')
4157 >>> c.ln(Decimal('10'))
4158 Decimal('2.30258509')
4159 >>> c.ln(Decimal('+Infinity'))
4160 Decimal('Infinity')
4162 return a.ln(context=self)
4164 def log10(self, a):
4165 """Returns the base 10 logarithm of the operand.
4167 >>> c = ExtendedContext.copy()
4168 >>> c.Emin = -999
4169 >>> c.Emax = 999
4170 >>> c.log10(Decimal('0'))
4171 Decimal('-Infinity')
4172 >>> c.log10(Decimal('0.001'))
4173 Decimal('-3')
4174 >>> c.log10(Decimal('1.000'))
4175 Decimal('0')
4176 >>> c.log10(Decimal('2'))
4177 Decimal('0.301029996')
4178 >>> c.log10(Decimal('10'))
4179 Decimal('1')
4180 >>> c.log10(Decimal('70'))
4181 Decimal('1.84509804')
4182 >>> c.log10(Decimal('+Infinity'))
4183 Decimal('Infinity')
4185 return a.log10(context=self)
4187 def logb(self, a):
4188 """ Returns the exponent of the magnitude of the operand's MSD.
4190 The result is the integer which is the exponent of the magnitude
4191 of the most significant digit of the operand (as though the
4192 operand were truncated to a single digit while maintaining the
4193 value of that digit and without limiting the resulting exponent).
4195 >>> ExtendedContext.logb(Decimal('250'))
4196 Decimal('2')
4197 >>> ExtendedContext.logb(Decimal('2.50'))
4198 Decimal('0')
4199 >>> ExtendedContext.logb(Decimal('0.03'))
4200 Decimal('-2')
4201 >>> ExtendedContext.logb(Decimal('0'))
4202 Decimal('-Infinity')
4204 return a.logb(context=self)
4206 def logical_and(self, a, b):
4207 """Applies the logical operation 'and' between each operand's digits.
4209 The operands must be both logical numbers.
4211 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4212 Decimal('0')
4213 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4214 Decimal('0')
4215 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4216 Decimal('0')
4217 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4218 Decimal('1')
4219 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4220 Decimal('1000')
4221 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4222 Decimal('10')
4224 return a.logical_and(b, context=self)
4226 def logical_invert(self, a):
4227 """Invert all the digits in the operand.
4229 The operand must be a logical number.
4231 >>> ExtendedContext.logical_invert(Decimal('0'))
4232 Decimal('111111111')
4233 >>> ExtendedContext.logical_invert(Decimal('1'))
4234 Decimal('111111110')
4235 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4236 Decimal('0')
4237 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4238 Decimal('10101010')
4240 return a.logical_invert(context=self)
4242 def logical_or(self, a, b):
4243 """Applies the logical operation 'or' between each operand's digits.
4245 The operands must be both logical numbers.
4247 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4248 Decimal('0')
4249 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4250 Decimal('1')
4251 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4252 Decimal('1')
4253 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4254 Decimal('1')
4255 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4256 Decimal('1110')
4257 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4258 Decimal('1110')
4260 return a.logical_or(b, context=self)
4262 def logical_xor(self, a, b):
4263 """Applies the logical operation 'xor' between each operand's digits.
4265 The operands must be both logical numbers.
4267 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4268 Decimal('0')
4269 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4270 Decimal('1')
4271 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4272 Decimal('1')
4273 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4274 Decimal('0')
4275 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4276 Decimal('110')
4277 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4278 Decimal('1101')
4280 return a.logical_xor(b, context=self)
4282 def max(self, a,b):
4283 """max compares two values numerically and returns the maximum.
4285 If either operand is a NaN then the general rules apply.
4286 Otherwise, the operands are compared as though by the compare
4287 operation. If they are numerically equal then the left-hand operand
4288 is chosen as the result. Otherwise the maximum (closer to positive
4289 infinity) of the two operands is chosen as the result.
4291 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4292 Decimal('3')
4293 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4294 Decimal('3')
4295 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4296 Decimal('1')
4297 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4298 Decimal('7')
4300 return a.max(b, context=self)
4302 def max_mag(self, a, b):
4303 """Compares the values numerically with their sign ignored."""
4304 return a.max_mag(b, context=self)
4306 def min(self, a,b):
4307 """min compares two values numerically and returns the minimum.
4309 If either operand is a NaN then the general rules apply.
4310 Otherwise, the operands are compared as though by the compare
4311 operation. If they are numerically equal then the left-hand operand
4312 is chosen as the result. Otherwise the minimum (closer to negative
4313 infinity) of the two operands is chosen as the result.
4315 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4316 Decimal('2')
4317 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4318 Decimal('-10')
4319 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4320 Decimal('1.0')
4321 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4322 Decimal('7')
4324 return a.min(b, context=self)
4326 def min_mag(self, a, b):
4327 """Compares the values numerically with their sign ignored."""
4328 return a.min_mag(b, context=self)
4330 def minus(self, a):
4331 """Minus corresponds to unary prefix minus in Python.
4333 The operation is evaluated using the same rules as subtract; the
4334 operation minus(a) is calculated as subtract('0', a) where the '0'
4335 has the same exponent as the operand.
4337 >>> ExtendedContext.minus(Decimal('1.3'))
4338 Decimal('-1.3')
4339 >>> ExtendedContext.minus(Decimal('-1.3'))
4340 Decimal('1.3')
4342 return a.__neg__(context=self)
4344 def multiply(self, a, b):
4345 """multiply multiplies two operands.
4347 If either operand is a special value then the general rules apply.
4348 Otherwise, the operands are multiplied together ('long multiplication'),
4349 resulting in a number which may be as long as the sum of the lengths
4350 of the two operands.
4352 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4353 Decimal('3.60')
4354 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4355 Decimal('21')
4356 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4357 Decimal('0.72')
4358 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4359 Decimal('-0.0')
4360 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4361 Decimal('4.28135971E+11')
4363 return a.__mul__(b, context=self)
4365 def next_minus(self, a):
4366 """Returns the largest representable number smaller than a.
4368 >>> c = ExtendedContext.copy()
4369 >>> c.Emin = -999
4370 >>> c.Emax = 999
4371 >>> ExtendedContext.next_minus(Decimal('1'))
4372 Decimal('0.999999999')
4373 >>> c.next_minus(Decimal('1E-1007'))
4374 Decimal('0E-1007')
4375 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4376 Decimal('-1.00000004')
4377 >>> c.next_minus(Decimal('Infinity'))
4378 Decimal('9.99999999E+999')
4380 return a.next_minus(context=self)
4382 def next_plus(self, a):
4383 """Returns the smallest representable number larger than a.
4385 >>> c = ExtendedContext.copy()
4386 >>> c.Emin = -999
4387 >>> c.Emax = 999
4388 >>> ExtendedContext.next_plus(Decimal('1'))
4389 Decimal('1.00000001')
4390 >>> c.next_plus(Decimal('-1E-1007'))
4391 Decimal('-0E-1007')
4392 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4393 Decimal('-1.00000002')
4394 >>> c.next_plus(Decimal('-Infinity'))
4395 Decimal('-9.99999999E+999')
4397 return a.next_plus(context=self)
4399 def next_toward(self, a, b):
4400 """Returns the number closest to a, in direction towards b.
4402 The result is the closest representable number from the first
4403 operand (but not the first operand) that is in the direction
4404 towards the second operand, unless the operands have the same
4405 value.
4407 >>> c = ExtendedContext.copy()
4408 >>> c.Emin = -999
4409 >>> c.Emax = 999
4410 >>> c.next_toward(Decimal('1'), Decimal('2'))
4411 Decimal('1.00000001')
4412 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4413 Decimal('-0E-1007')
4414 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4415 Decimal('-1.00000002')
4416 >>> c.next_toward(Decimal('1'), Decimal('0'))
4417 Decimal('0.999999999')
4418 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4419 Decimal('0E-1007')
4420 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4421 Decimal('-1.00000004')
4422 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4423 Decimal('-0.00')
4425 return a.next_toward(b, context=self)
4427 def normalize(self, a):
4428 """normalize reduces an operand to its simplest form.
4430 Essentially a plus operation with all trailing zeros removed from the
4431 result.
4433 >>> ExtendedContext.normalize(Decimal('2.1'))
4434 Decimal('2.1')
4435 >>> ExtendedContext.normalize(Decimal('-2.0'))
4436 Decimal('-2')
4437 >>> ExtendedContext.normalize(Decimal('1.200'))
4438 Decimal('1.2')
4439 >>> ExtendedContext.normalize(Decimal('-120'))
4440 Decimal('-1.2E+2')
4441 >>> ExtendedContext.normalize(Decimal('120.00'))
4442 Decimal('1.2E+2')
4443 >>> ExtendedContext.normalize(Decimal('0.00'))
4444 Decimal('0')
4446 return a.normalize(context=self)
4448 def number_class(self, a):
4449 """Returns an indication of the class of the operand.
4451 The class is one of the following strings:
4452 -sNaN
4453 -NaN
4454 -Infinity
4455 -Normal
4456 -Subnormal
4457 -Zero
4458 +Zero
4459 +Subnormal
4460 +Normal
4461 +Infinity
4463 >>> c = Context(ExtendedContext)
4464 >>> c.Emin = -999
4465 >>> c.Emax = 999
4466 >>> c.number_class(Decimal('Infinity'))
4467 '+Infinity'
4468 >>> c.number_class(Decimal('1E-10'))
4469 '+Normal'
4470 >>> c.number_class(Decimal('2.50'))
4471 '+Normal'
4472 >>> c.number_class(Decimal('0.1E-999'))
4473 '+Subnormal'
4474 >>> c.number_class(Decimal('0'))
4475 '+Zero'
4476 >>> c.number_class(Decimal('-0'))
4477 '-Zero'
4478 >>> c.number_class(Decimal('-0.1E-999'))
4479 '-Subnormal'
4480 >>> c.number_class(Decimal('-1E-10'))
4481 '-Normal'
4482 >>> c.number_class(Decimal('-2.50'))
4483 '-Normal'
4484 >>> c.number_class(Decimal('-Infinity'))
4485 '-Infinity'
4486 >>> c.number_class(Decimal('NaN'))
4487 'NaN'
4488 >>> c.number_class(Decimal('-NaN'))
4489 'NaN'
4490 >>> c.number_class(Decimal('sNaN'))
4491 'sNaN'
4493 return a.number_class(context=self)
4495 def plus(self, a):
4496 """Plus corresponds to unary prefix plus in Python.
4498 The operation is evaluated using the same rules as add; the
4499 operation plus(a) is calculated as add('0', a) where the '0'
4500 has the same exponent as the operand.
4502 >>> ExtendedContext.plus(Decimal('1.3'))
4503 Decimal('1.3')
4504 >>> ExtendedContext.plus(Decimal('-1.3'))
4505 Decimal('-1.3')
4507 return a.__pos__(context=self)
4509 def power(self, a, b, modulo=None):
4510 """Raises a to the power of b, to modulo if given.
4512 With two arguments, compute a**b. If a is negative then b
4513 must be integral. The result will be inexact unless b is
4514 integral and the result is finite and can be expressed exactly
4515 in 'precision' digits.
4517 With three arguments, compute (a**b) % modulo. For the
4518 three argument form, the following restrictions on the
4519 arguments hold:
4521 - all three arguments must be integral
4522 - b must be nonnegative
4523 - at least one of a or b must be nonzero
4524 - modulo must be nonzero and have at most 'precision' digits
4526 The result of pow(a, b, modulo) is identical to the result
4527 that would be obtained by computing (a**b) % modulo with
4528 unbounded precision, but is computed more efficiently. It is
4529 always exact.
4531 >>> c = ExtendedContext.copy()
4532 >>> c.Emin = -999
4533 >>> c.Emax = 999
4534 >>> c.power(Decimal('2'), Decimal('3'))
4535 Decimal('8')
4536 >>> c.power(Decimal('-2'), Decimal('3'))
4537 Decimal('-8')
4538 >>> c.power(Decimal('2'), Decimal('-3'))
4539 Decimal('0.125')
4540 >>> c.power(Decimal('1.7'), Decimal('8'))
4541 Decimal('69.7575744')
4542 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4543 Decimal('2.00000000')
4544 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4545 Decimal('0')
4546 >>> c.power(Decimal('Infinity'), Decimal('0'))
4547 Decimal('1')
4548 >>> c.power(Decimal('Infinity'), Decimal('1'))
4549 Decimal('Infinity')
4550 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4551 Decimal('-0')
4552 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4553 Decimal('1')
4554 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4555 Decimal('-Infinity')
4556 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4557 Decimal('Infinity')
4558 >>> c.power(Decimal('0'), Decimal('0'))
4559 Decimal('NaN')
4561 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4562 Decimal('11')
4563 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4564 Decimal('-11')
4565 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4566 Decimal('1')
4567 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4568 Decimal('11')
4569 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4570 Decimal('11729830')
4571 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4572 Decimal('-0')
4573 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4574 Decimal('1')
4576 return a.__pow__(b, modulo, context=self)
4578 def quantize(self, a, b):
4579 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4581 The coefficient of the result is derived from that of the left-hand
4582 operand. It may be rounded using the current rounding setting (if the
4583 exponent is being increased), multiplied by a positive power of ten (if
4584 the exponent is being decreased), or is unchanged (if the exponent is
4585 already equal to that of the right-hand operand).
4587 Unlike other operations, if the length of the coefficient after the
4588 quantize operation would be greater than precision then an Invalid
4589 operation condition is raised. This guarantees that, unless there is
4590 an error condition, the exponent of the result of a quantize is always
4591 equal to that of the right-hand operand.
4593 Also unlike other operations, quantize will never raise Underflow, even
4594 if the result is subnormal and inexact.
4596 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4597 Decimal('2.170')
4598 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4599 Decimal('2.17')
4600 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4601 Decimal('2.2')
4602 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4603 Decimal('2')
4604 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4605 Decimal('0E+1')
4606 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4607 Decimal('-Infinity')
4608 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4609 Decimal('NaN')
4610 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4611 Decimal('-0')
4612 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4613 Decimal('-0E+5')
4614 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4615 Decimal('NaN')
4616 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4617 Decimal('NaN')
4618 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4619 Decimal('217.0')
4620 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4621 Decimal('217')
4622 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4623 Decimal('2.2E+2')
4624 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4625 Decimal('2E+2')
4627 return a.quantize(b, context=self)
4629 def radix(self):
4630 """Just returns 10, as this is Decimal, :)
4632 >>> ExtendedContext.radix()
4633 Decimal('10')
4635 return Decimal(10)
4637 def remainder(self, a, b):
4638 """Returns the remainder from integer division.
4640 The result is the residue of the dividend after the operation of
4641 calculating integer division as described for divide-integer, rounded
4642 to precision digits if necessary. The sign of the result, if
4643 non-zero, is the same as that of the original dividend.
4645 This operation will fail under the same conditions as integer division
4646 (that is, if integer division on the same two operands would fail, the
4647 remainder cannot be calculated).
4649 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4650 Decimal('2.1')
4651 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4652 Decimal('1')
4653 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4654 Decimal('-1')
4655 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4656 Decimal('0.2')
4657 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4658 Decimal('0.1')
4659 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4660 Decimal('1.0')
4662 return a.__mod__(b, context=self)
4664 def remainder_near(self, a, b):
4665 """Returns to be "a - b * n", where n is the integer nearest the exact
4666 value of "x / b" (if two integers are equally near then the even one
4667 is chosen). If the result is equal to 0 then its sign will be the
4668 sign of a.
4670 This operation will fail under the same conditions as integer division
4671 (that is, if integer division on the same two operands would fail, the
4672 remainder cannot be calculated).
4674 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4675 Decimal('-0.9')
4676 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4677 Decimal('-2')
4678 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4679 Decimal('1')
4680 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4681 Decimal('-1')
4682 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4683 Decimal('0.2')
4684 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4685 Decimal('0.1')
4686 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4687 Decimal('-0.3')
4689 return a.remainder_near(b, context=self)
4691 def rotate(self, a, b):
4692 """Returns a rotated copy of a, b times.
4694 The coefficient of the result is a rotated copy of the digits in
4695 the coefficient of the first operand. The number of places of
4696 rotation is taken from the absolute value of the second operand,
4697 with the rotation being to the left if the second operand is
4698 positive or to the right otherwise.
4700 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4701 Decimal('400000003')
4702 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4703 Decimal('12')
4704 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4705 Decimal('891234567')
4706 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4707 Decimal('123456789')
4708 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4709 Decimal('345678912')
4711 return a.rotate(b, context=self)
4713 def same_quantum(self, a, b):
4714 """Returns True if the two operands have the same exponent.
4716 The result is never affected by either the sign or the coefficient of
4717 either operand.
4719 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4720 False
4721 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4722 True
4723 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4724 False
4725 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4726 True
4728 return a.same_quantum(b)
4730 def scaleb (self, a, b):
4731 """Returns the first operand after adding the second value its exp.
4733 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4734 Decimal('0.0750')
4735 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4736 Decimal('7.50')
4737 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4738 Decimal('7.50E+3')
4740 return a.scaleb (b, context=self)
4742 def shift(self, a, b):
4743 """Returns a shifted copy of a, b times.
4745 The coefficient of the result is a shifted copy of the digits
4746 in the coefficient of the first operand. The number of places
4747 to shift is taken from the absolute value of the second operand,
4748 with the shift being to the left if the second operand is
4749 positive or to the right otherwise. Digits shifted into the
4750 coefficient are zeros.
4752 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4753 Decimal('400000000')
4754 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4755 Decimal('0')
4756 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4757 Decimal('1234567')
4758 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4759 Decimal('123456789')
4760 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4761 Decimal('345678900')
4763 return a.shift(b, context=self)
4765 def sqrt(self, a):
4766 """Square root of a non-negative number to context precision.
4768 If the result must be inexact, it is rounded using the round-half-even
4769 algorithm.
4771 >>> ExtendedContext.sqrt(Decimal('0'))
4772 Decimal('0')
4773 >>> ExtendedContext.sqrt(Decimal('-0'))
4774 Decimal('-0')
4775 >>> ExtendedContext.sqrt(Decimal('0.39'))
4776 Decimal('0.624499800')
4777 >>> ExtendedContext.sqrt(Decimal('100'))
4778 Decimal('10')
4779 >>> ExtendedContext.sqrt(Decimal('1'))
4780 Decimal('1')
4781 >>> ExtendedContext.sqrt(Decimal('1.0'))
4782 Decimal('1.0')
4783 >>> ExtendedContext.sqrt(Decimal('1.00'))
4784 Decimal('1.0')
4785 >>> ExtendedContext.sqrt(Decimal('7'))
4786 Decimal('2.64575131')
4787 >>> ExtendedContext.sqrt(Decimal('10'))
4788 Decimal('3.16227766')
4789 >>> ExtendedContext.prec
4792 return a.sqrt(context=self)
4794 def subtract(self, a, b):
4795 """Return the difference between the two operands.
4797 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4798 Decimal('0.23')
4799 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4800 Decimal('0.00')
4801 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4802 Decimal('-0.77')
4804 return a.__sub__(b, context=self)
4806 def to_eng_string(self, a):
4807 """Converts a number to a string, using scientific notation.
4809 The operation is not affected by the context.
4811 return a.to_eng_string(context=self)
4813 def to_sci_string(self, a):
4814 """Converts a number to a string, using scientific notation.
4816 The operation is not affected by the context.
4818 return a.__str__(context=self)
4820 def to_integral_exact(self, a):
4821 """Rounds to an integer.
4823 When the operand has a negative exponent, the result is the same
4824 as using the quantize() operation using the given operand as the
4825 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4826 of the operand as the precision setting; Inexact and Rounded flags
4827 are allowed in this operation. The rounding mode is taken from the
4828 context.
4830 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4831 Decimal('2')
4832 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4833 Decimal('100')
4834 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4835 Decimal('100')
4836 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4837 Decimal('102')
4838 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4839 Decimal('-102')
4840 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4841 Decimal('1.0E+6')
4842 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4843 Decimal('7.89E+77')
4844 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4845 Decimal('-Infinity')
4847 return a.to_integral_exact(context=self)
4849 def to_integral_value(self, a):
4850 """Rounds to an integer.
4852 When the operand has a negative exponent, the result is the same
4853 as using the quantize() operation using the given operand as the
4854 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4855 of the operand as the precision setting, except that no flags will
4856 be set. The rounding mode is taken from the context.
4858 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4859 Decimal('2')
4860 >>> ExtendedContext.to_integral_value(Decimal('100'))
4861 Decimal('100')
4862 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4863 Decimal('100')
4864 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4865 Decimal('102')
4866 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4867 Decimal('-102')
4868 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4869 Decimal('1.0E+6')
4870 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4871 Decimal('7.89E+77')
4872 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4873 Decimal('-Infinity')
4875 return a.to_integral_value(context=self)
4877 # the method name changed, but we provide also the old one, for compatibility
4878 to_integral = to_integral_value
4880 class _WorkRep(object):
4881 __slots__ = ('sign','int','exp')
4882 # sign: 0 or 1
4883 # int: int
4884 # exp: None, int, or string
4886 def __init__(self, value=None):
4887 if value is None:
4888 self.sign = None
4889 self.int = 0
4890 self.exp = None
4891 elif isinstance(value, Decimal):
4892 self.sign = value._sign
4893 self.int = int(value._int)
4894 self.exp = value._exp
4895 else:
4896 # assert isinstance(value, tuple)
4897 self.sign = value[0]
4898 self.int = value[1]
4899 self.exp = value[2]
4901 def __repr__(self):
4902 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4904 __str__ = __repr__
4908 def _normalize(op1, op2, prec = 0):
4909 """Normalizes op1, op2 to have the same exp and length of coefficient.
4911 Done during addition.
4913 if op1.exp < op2.exp:
4914 tmp = op2
4915 other = op1
4916 else:
4917 tmp = op1
4918 other = op2
4920 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4921 # Then adding 10**exp to tmp has the same effect (after rounding)
4922 # as adding any positive quantity smaller than 10**exp; similarly
4923 # for subtraction. So if other is smaller than 10**exp we replace
4924 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4925 tmp_len = len(str(tmp.int))
4926 other_len = len(str(other.int))
4927 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4928 if other_len + other.exp - 1 < exp:
4929 other.int = 1
4930 other.exp = exp
4932 tmp.int *= 10 ** (tmp.exp - other.exp)
4933 tmp.exp = other.exp
4934 return op1, op2
4936 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4938 # This function from Tim Peters was taken from here:
4939 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4940 # The correction being in the function definition is for speed, and
4941 # the whole function is not resolved with math.log because of avoiding
4942 # the use of floats.
4943 def _nbits(n, correction = {
4944 '0': 4, '1': 3, '2': 2, '3': 2,
4945 '4': 1, '5': 1, '6': 1, '7': 1,
4946 '8': 0, '9': 0, 'a': 0, 'b': 0,
4947 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4948 """Number of bits in binary representation of the positive integer n,
4949 or 0 if n == 0.
4951 if n < 0:
4952 raise ValueError("The argument to _nbits should be nonnegative.")
4953 hex_n = "%x" % n
4954 return 4*len(hex_n) - correction[hex_n[0]]
4956 def _sqrt_nearest(n, a):
4957 """Closest integer to the square root of the positive integer n. a is
4958 an initial approximation to the square root. Any positive integer
4959 will do for a, but the closer a is to the square root of n the
4960 faster convergence will be.
4963 if n <= 0 or a <= 0:
4964 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4967 while a != b:
4968 b, a = a, a--n//a>>1
4969 return a
4971 def _rshift_nearest(x, shift):
4972 """Given an integer x and a nonnegative integer shift, return closest
4973 integer to x / 2**shift; use round-to-even in case of a tie.
4976 b, q = 1 << shift, x >> shift
4977 return q + (2*(x & (b-1)) + (q&1) > b)
4979 def _div_nearest(a, b):
4980 """Closest integer to a/b, a and b positive integers; rounds to even
4981 in the case of a tie.
4984 q, r = divmod(a, b)
4985 return q + (2*r + (q&1) > b)
4987 def _ilog(x, M, L = 8):
4988 """Integer approximation to M*log(x/M), with absolute error boundable
4989 in terms only of x/M.
4991 Given positive integers x and M, return an integer approximation to
4992 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4993 between the approximation and the exact result is at most 22. For
4994 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4995 both cases these are upper bounds on the error; it will usually be
4996 much smaller."""
4998 # The basic algorithm is the following: let log1p be the function
4999 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5000 # the reduction
5002 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5004 # repeatedly until the argument to log1p is small (< 2**-L in
5005 # absolute value). For small y we can use the Taylor series
5006 # expansion
5008 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5010 # truncating at T such that y**T is small enough. The whole
5011 # computation is carried out in a form of fixed-point arithmetic,
5012 # with a real number z being represented by an integer
5013 # approximation to z*M. To avoid loss of precision, the y below
5014 # is actually an integer approximation to 2**R*y*M, where R is the
5015 # number of reductions performed so far.
5017 y = x-M
5018 # argument reduction; R = number of reductions performed
5019 R = 0
5020 while (R <= L and abs(y) << L-R >= M or
5021 R > L and abs(y) >> R-L >= M):
5022 y = _div_nearest((M*y) << 1,
5023 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5024 R += 1
5026 # Taylor series with T terms
5027 T = -int(-10*len(str(M))//(3*L))
5028 yshift = _rshift_nearest(y, R)
5029 w = _div_nearest(M, T)
5030 for k in range(T-1, 0, -1):
5031 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5033 return _div_nearest(w*y, M)
5035 def _dlog10(c, e, p):
5036 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5037 approximation to 10**p * log10(c*10**e), with an absolute error of
5038 at most 1. Assumes that c*10**e is not exactly 1."""
5040 # increase precision by 2; compensate for this by dividing
5041 # final result by 100
5042 p += 2
5044 # write c*10**e as d*10**f with either:
5045 # f >= 0 and 1 <= d <= 10, or
5046 # f <= 0 and 0.1 <= d <= 1.
5047 # Thus for c*10**e close to 1, f = 0
5048 l = len(str(c))
5049 f = e+l - (e+l >= 1)
5051 if p > 0:
5052 M = 10**p
5053 k = e+p-f
5054 if k >= 0:
5055 c *= 10**k
5056 else:
5057 c = _div_nearest(c, 10**-k)
5059 log_d = _ilog(c, M) # error < 5 + 22 = 27
5060 log_10 = _log10_digits(p) # error < 1
5061 log_d = _div_nearest(log_d*M, log_10)
5062 log_tenpower = f*M # exact
5063 else:
5064 log_d = 0 # error < 2.31
5065 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5067 return _div_nearest(log_tenpower+log_d, 100)
5069 def _dlog(c, e, p):
5070 """Given integers c, e and p with c > 0, compute an integer
5071 approximation to 10**p * log(c*10**e), with an absolute error of
5072 at most 1. Assumes that c*10**e is not exactly 1."""
5074 # Increase precision by 2. The precision increase is compensated
5075 # for at the end with a division by 100.
5076 p += 2
5078 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5079 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5080 # as 10**p * log(d) + 10**p*f * log(10).
5081 l = len(str(c))
5082 f = e+l - (e+l >= 1)
5084 # compute approximation to 10**p*log(d), with error < 27
5085 if p > 0:
5086 k = e+p-f
5087 if k >= 0:
5088 c *= 10**k
5089 else:
5090 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5092 # _ilog magnifies existing error in c by a factor of at most 10
5093 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5094 else:
5095 # p <= 0: just approximate the whole thing by 0; error < 2.31
5096 log_d = 0
5098 # compute approximation to f*10**p*log(10), with error < 11.
5099 if f:
5100 extra = len(str(abs(f)))-1
5101 if p + extra >= 0:
5102 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5103 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5104 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5105 else:
5106 f_log_ten = 0
5107 else:
5108 f_log_ten = 0
5110 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5111 return _div_nearest(f_log_ten + log_d, 100)
5113 class _Log10Memoize(object):
5114 """Class to compute, store, and allow retrieval of, digits of the
5115 constant log(10) = 2.302585.... This constant is needed by
5116 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5117 def __init__(self):
5118 self.digits = "23025850929940456840179914546843642076011014886"
5120 def getdigits(self, p):
5121 """Given an integer p >= 0, return floor(10**p)*log(10).
5123 For example, self.getdigits(3) returns 2302.
5125 # digits are stored as a string, for quick conversion to
5126 # integer in the case that we've already computed enough
5127 # digits; the stored digits should always be correct
5128 # (truncated, not rounded to nearest).
5129 if p < 0:
5130 raise ValueError("p should be nonnegative")
5132 if p >= len(self.digits):
5133 # compute p+3, p+6, p+9, ... digits; continue until at
5134 # least one of the extra digits is nonzero
5135 extra = 3
5136 while True:
5137 # compute p+extra digits, correct to within 1ulp
5138 M = 10**(p+extra+2)
5139 digits = str(_div_nearest(_ilog(10*M, M), 100))
5140 if digits[-extra:] != '0'*extra:
5141 break
5142 extra += 3
5143 # keep all reliable digits so far; remove trailing zeros
5144 # and next nonzero digit
5145 self.digits = digits.rstrip('0')[:-1]
5146 return int(self.digits[:p+1])
5148 _log10_digits = _Log10Memoize().getdigits
5150 def _iexp(x, M, L=8):
5151 """Given integers x and M, M > 0, such that x/M is small in absolute
5152 value, compute an integer approximation to M*exp(x/M). For 0 <=
5153 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5154 is usually much smaller)."""
5156 # Algorithm: to compute exp(z) for a real number z, first divide z
5157 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5158 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5159 # series
5161 # expm1(x) = x + x**2/2! + x**3/3! + ...
5163 # Now use the identity
5165 # expm1(2x) = expm1(x)*(expm1(x)+2)
5167 # R times to compute the sequence expm1(z/2**R),
5168 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5170 # Find R such that x/2**R/M <= 2**-L
5171 R = _nbits((x<<L)//M)
5173 # Taylor series. (2**L)**T > M
5174 T = -int(-10*len(str(M))//(3*L))
5175 y = _div_nearest(x, T)
5176 Mshift = M<<R
5177 for i in range(T-1, 0, -1):
5178 y = _div_nearest(x*(Mshift + y), Mshift * i)
5180 # Expansion
5181 for k in range(R-1, -1, -1):
5182 Mshift = M<<(k+2)
5183 y = _div_nearest(y*(y+Mshift), Mshift)
5185 return M+y
5187 def _dexp(c, e, p):
5188 """Compute an approximation to exp(c*10**e), with p decimal places of
5189 precision.
5191 Returns integers d, f such that:
5193 10**(p-1) <= d <= 10**p, and
5194 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5196 In other words, d*10**f is an approximation to exp(c*10**e) with p
5197 digits of precision, and with an error in d of at most 1. This is
5198 almost, but not quite, the same as the error being < 1ulp: when d
5199 = 10**(p-1) the error could be up to 10 ulp."""
5201 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5202 p += 2
5204 # compute log(10) with extra precision = adjusted exponent of c*10**e
5205 extra = max(0, e + len(str(c)) - 1)
5206 q = p + extra
5208 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5209 # rounding down
5210 shift = e+q
5211 if shift >= 0:
5212 cshift = c*10**shift
5213 else:
5214 cshift = c//10**-shift
5215 quot, rem = divmod(cshift, _log10_digits(q))
5217 # reduce remainder back to original precision
5218 rem = _div_nearest(rem, 10**extra)
5220 # error in result of _iexp < 120; error after division < 0.62
5221 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5223 def _dpower(xc, xe, yc, ye, p):
5224 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5225 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5227 10**(p-1) <= c <= 10**p, and
5228 (c-1)*10**e < x**y < (c+1)*10**e
5230 in other words, c*10**e is an approximation to x**y with p digits
5231 of precision, and with an error in c of at most 1. (This is
5232 almost, but not quite, the same as the error being < 1ulp: when c
5233 == 10**(p-1) we can only guarantee error < 10ulp.)
5235 We assume that: x is positive and not equal to 1, and y is nonzero.
5238 # Find b such that 10**(b-1) <= |y| <= 10**b
5239 b = len(str(abs(yc))) + ye
5241 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5242 lxc = _dlog(xc, xe, p+b+1)
5244 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5245 shift = ye-b
5246 if shift >= 0:
5247 pc = lxc*yc*10**shift
5248 else:
5249 pc = _div_nearest(lxc*yc, 10**-shift)
5251 if pc == 0:
5252 # we prefer a result that isn't exactly 1; this makes it
5253 # easier to compute a correctly rounded result in __pow__
5254 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5255 coeff, exp = 10**(p-1)+1, 1-p
5256 else:
5257 coeff, exp = 10**p-1, -p
5258 else:
5259 coeff, exp = _dexp(pc, -(p+1), p+1)
5260 coeff = _div_nearest(coeff, 10)
5261 exp += 1
5263 return coeff, exp
5265 def _log10_lb(c, correction = {
5266 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5267 '6': 23, '7': 16, '8': 10, '9': 5}):
5268 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5269 if c <= 0:
5270 raise ValueError("The argument to _log10_lb should be nonnegative.")
5271 str_c = str(c)
5272 return 100*len(str_c) - correction[str_c[0]]
5274 ##### Helper Functions ####################################################
5276 def _convert_other(other, raiseit=False):
5277 """Convert other to Decimal.
5279 Verifies that it's ok to use in an implicit construction.
5281 if isinstance(other, Decimal):
5282 return other
5283 if isinstance(other, int):
5284 return Decimal(other)
5285 if raiseit:
5286 raise TypeError("Unable to convert %s to Decimal" % other)
5287 return NotImplemented
5289 ##### Setup Specific Contexts ############################################
5291 # The default context prototype used by Context()
5292 # Is mutable, so that new contexts can have different default values
5294 DefaultContext = Context(
5295 prec=28, rounding=ROUND_HALF_EVEN,
5296 traps=[DivisionByZero, Overflow, InvalidOperation],
5297 flags=[],
5298 Emax=999999999,
5299 Emin=-999999999,
5300 capitals=1
5303 # Pre-made alternate contexts offered by the specification
5304 # Don't change these; the user should be able to select these
5305 # contexts and be able to reproduce results from other implementations
5306 # of the spec.
5308 BasicContext = Context(
5309 prec=9, rounding=ROUND_HALF_UP,
5310 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5311 flags=[],
5314 ExtendedContext = Context(
5315 prec=9, rounding=ROUND_HALF_EVEN,
5316 traps=[],
5317 flags=[],
5321 ##### crud for parsing strings #############################################
5323 # Regular expression used for parsing numeric strings. Additional
5324 # comments:
5326 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5327 # whitespace. But note that the specification disallows whitespace in
5328 # a numeric string.
5330 # 2. For finite numbers (not infinities and NaNs) the body of the
5331 # number between the optional sign and the optional exponent must have
5332 # at least one decimal digit, possibly after the decimal point. The
5333 # lookahead expression '(?=\d|\.\d)' checks this.
5335 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5336 # other meaning for \d than the numbers [0-9].
5338 import re
5339 _parser = re.compile(r""" # A numeric string consists of:
5340 # \s*
5341 (?P<sign>[-+])? # an optional sign, followed by either...
5343 (?=\d|\.\d) # ...a number (with at least one digit)
5344 (?P<int>\d*) # consisting of a (possibly empty) integer part
5345 (\.(?P<frac>\d*))? # followed by an optional fractional part
5346 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5348 Inf(inity)? # ...an infinity, or...
5350 (?P<signal>s)? # ...an (optionally signaling)
5351 NaN # NaN
5352 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5354 # \s*
5356 """, re.VERBOSE | re.IGNORECASE).match
5358 _all_zeros = re.compile('0*$').match
5359 _exact_half = re.compile('50*$').match
5361 ##### PEP3101 support functions ##############################################
5362 # The functions parse_format_specifier and format_align have little to do
5363 # with the Decimal class, and could potentially be reused for other pure
5364 # Python numeric classes that want to implement __format__
5366 # A format specifier for Decimal looks like:
5368 # [[fill]align][sign][0][minimumwidth][.precision][type]
5371 _parse_format_specifier_regex = re.compile(r"""\A
5373 (?P<fill>.)?
5374 (?P<align>[<>=^])
5376 (?P<sign>[-+ ])?
5377 (?P<zeropad>0)?
5378 (?P<minimumwidth>(?!0)\d+)?
5379 (?:\.(?P<precision>0|(?!0)\d+))?
5380 (?P<type>[eEfFgG%])?
5382 """, re.VERBOSE)
5384 del re
5386 def _parse_format_specifier(format_spec):
5387 """Parse and validate a format specifier.
5389 Turns a standard numeric format specifier into a dict, with the
5390 following entries:
5392 fill: fill character to pad field to minimum width
5393 align: alignment type, either '<', '>', '=' or '^'
5394 sign: either '+', '-' or ' '
5395 minimumwidth: nonnegative integer giving minimum width
5396 precision: nonnegative integer giving precision, or None
5397 type: one of the characters 'eEfFgG%', or None
5398 unicode: either True or False (always True for Python 3.x)
5401 m = _parse_format_specifier_regex.match(format_spec)
5402 if m is None:
5403 raise ValueError("Invalid format specifier: " + format_spec)
5405 # get the dictionary
5406 format_dict = m.groupdict()
5408 # defaults for fill and alignment
5409 fill = format_dict['fill']
5410 align = format_dict['align']
5411 if format_dict.pop('zeropad') is not None:
5412 # in the face of conflict, refuse the temptation to guess
5413 if fill is not None and fill != '0':
5414 raise ValueError("Fill character conflicts with '0'"
5415 " in format specifier: " + format_spec)
5416 if align is not None and align != '=':
5417 raise ValueError("Alignment conflicts with '0' in "
5418 "format specifier: " + format_spec)
5419 fill = '0'
5420 align = '='
5421 format_dict['fill'] = fill or ' '
5422 format_dict['align'] = align or '<'
5424 if format_dict['sign'] is None:
5425 format_dict['sign'] = '-'
5427 # turn minimumwidth and precision entries into integers.
5428 # minimumwidth defaults to 0; precision remains None if not given
5429 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5430 if format_dict['precision'] is not None:
5431 format_dict['precision'] = int(format_dict['precision'])
5433 # if format type is 'g' or 'G' then a precision of 0 makes little
5434 # sense; convert it to 1. Same if format type is unspecified.
5435 if format_dict['precision'] == 0:
5436 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5437 format_dict['precision'] = 1
5439 # record whether return type should be str or unicode
5440 format_dict['unicode'] = True
5442 return format_dict
5444 def _format_align(body, spec_dict):
5445 """Given an unpadded, non-aligned numeric string, add padding and
5446 aligment to conform with the given format specifier dictionary (as
5447 output from parse_format_specifier).
5449 It's assumed that if body is negative then it starts with '-'.
5450 Any leading sign ('-' or '+') is stripped from the body before
5451 applying the alignment and padding rules, and replaced in the
5452 appropriate position.
5455 # figure out the sign; we only examine the first character, so if
5456 # body has leading whitespace the results may be surprising.
5457 if len(body) > 0 and body[0] in '-+':
5458 sign = body[0]
5459 body = body[1:]
5460 else:
5461 sign = ''
5463 if sign != '-':
5464 if spec_dict['sign'] in ' +':
5465 sign = spec_dict['sign']
5466 else:
5467 sign = ''
5469 # how much extra space do we have to play with?
5470 minimumwidth = spec_dict['minimumwidth']
5471 fill = spec_dict['fill']
5472 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5474 align = spec_dict['align']
5475 if align == '<':
5476 result = padding + sign + body
5477 elif align == '>':
5478 result = sign + body + padding
5479 elif align == '=':
5480 result = sign + padding + body
5481 else: #align == '^'
5482 half = len(padding)//2
5483 result = padding[:half] + sign + body + padding[half:]
5485 return result
5487 ##### Useful Constants (internal use only) ################################
5489 # Reusable defaults
5490 Inf = Decimal('Inf')
5491 negInf = Decimal('-Inf')
5492 NaN = Decimal('NaN')
5493 Dec_0 = Decimal(0)
5494 Dec_p1 = Decimal(1)
5495 Dec_n1 = Decimal(-1)
5497 # Infsign[sign] is infinity w/ that sign
5498 Infsign = (Inf, negInf)
5502 if __name__ == '__main__':
5503 import doctest, sys
5504 doctest.testmod(sys.modules[__name__])