1 # Copyright (c) 2004 Python Software Foundation.
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>
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.
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)
52 >>> Decimal('123.45e12345678901234567890')
53 Decimal('1.2345E+12345678901234567892')
54 >>> Decimal('1.33') + Decimal('1.27')
56 >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
59 >>> print(dig / Decimal(3))
61 >>> getcontext().prec = 18
62 >>> print(dig / Decimal(3))
66 >>> print(Decimal(3).sqrt())
68 >>> print(Decimal(3) ** 123)
69 4.85192780976896427E+58
70 >>> inf = Decimal(1) / Decimal(0)
73 >>> neginf = Decimal(-1) / Decimal(0)
76 >>> print(neginf + inf)
78 >>> print(neginf * inf)
82 >>> getcontext().traps[DivisionByZero] = 1
84 Traceback (most recent call last):
88 decimal.DivisionByZero: x / 0
90 >>> c.traps[InvalidOperation] = 0
91 >>> print(c.flags[InvalidOperation])
93 >>> c.divide(Decimal(0), Decimal(0))
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])
120 'Decimal', 'Context',
123 'DefaultContext', 'BasicContext', 'ExtendedContext',
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
141 from collections
import namedtuple
as _namedtuple
142 DecimalTuple
= _namedtuple('DecimalTuple', 'sign digits exponent')
144 DecimalTuple
= lambda *args
: args
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'
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
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
):
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
204 x._rescale( non-integer )
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
):
218 ans
= _dec_from_triple(args
[0]._sign
, args
[0]._int
, 'n', True)
219 return ans
._fix
_nan
(context
)
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
):
232 class DivisionByZero(DecimalException
, ZeroDivisionError):
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
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
245 def handle(self
, context
, sign
, *args
):
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
):
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
):
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
):
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
341 def handle(self
, context
, sign
, *args
):
342 if context
.rounding
in (ROUND_HALF_UP
, ROUND_HALF_EVEN
,
343 ROUND_HALF_DOWN
, ROUND_UP
):
346 if context
.rounding
== ROUND_CEILING
:
348 return _dec_from_triple(sign
, '9'*context
.prec
,
349 context
.Emax
-context
.prec
+1)
351 if context
.rounding
== ROUND_FLOOR
:
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.
393 # Python was compiled without threads; create a mock object instead
395 class MockThreading(object):
396 def local(self
, sys
=sys
):
397 return sys
.modules
[__name__
]
398 threading
= MockThreading()
399 del sys
, MockThreading
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
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.
426 return threading
.currentThread().__decimal
_context
__
427 except AttributeError:
429 threading
.currentThread().__decimal
_context
__ = context
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.
446 return _local
.__decimal
_context
__
447 except AttributeError:
449 _local
.__decimal
_context
__ = 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
468 with localcontext() as ctx:
470 # Rest of sin calculation algorithm
471 # uses a precision 2 greater than normal
472 return +s # Convert result to normal precision
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()
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
517 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
519 >>> Decimal(314) # int
521 >>> Decimal(Decimal(314)) # another decimal instance
523 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
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
535 self
= object.__new
__(cls
)
538 # REs insist on real strings, so we can too.
539 if isinstance(value
, str):
540 m
= _parser(value
.strip())
543 context
= getcontext()
544 return context
._raise
_error
(ConversionSyntax
,
545 "Invalid literal for Decimal: %r" % value
)
547 if m
.group('sign') == "-":
551 intpart
= m
.group('int')
552 if intpart
is not None:
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
)
560 self
._int
= intpart
.lstrip('0') or '0'
562 self
._is
_special
= False
564 diag
= m
.group('diag')
567 self
._int
= diag
.lstrip('0')
568 if m
.group('signal'):
576 self
._is
_special
= True
580 if isinstance(value
, int):
586 self
._int
= str(abs(value
))
587 self
._is
_special
= False
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
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
606 # tuple/list conversion (possibly from as_tuple())
607 if isinstance(value
, (list,tuple)):
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]
619 # infinity: value[1] is ignored
622 self
._is
_special
= True
624 # process and validate the digits in value[1]
626 for digit
in value
[1]:
627 if isinstance(digit
, int) and 0 <= digit
<= 9:
629 if digits
or digit
!= 0:
632 raise ValueError("The second value in the tuple must "
633 "be composed of integers in the range "
635 if value
[2] in ('n', 'N'):
636 # NaN: digits form the diagnostic
637 self
._int
= ''.join(map(str, digits
))
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]))
644 self
._is
_special
= False
646 raise ValueError("The third value in the tuple must "
647 "be an integer, or one of the "
648 "strings 'F', 'n', 'N'.")
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
)
658 """Returns whether the number is not actually one.
672 def _isinfinity(self
):
673 """Returns whether the number is infinite
675 0 if finite or not a number
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
692 Done before operations.
695 self_is_nan
= self
._isnan
()
699 other_is_nan
= other
._isnan
()
701 if self_is_nan
or other_is_nan
:
703 context
= getcontext()
706 return context
._raise
_error
(InvalidOperation
, 'sNaN',
708 if other_is_nan
== 2:
709 return context
._raise
_error
(InvalidOperation
, 'sNaN',
712 return self
._fix
_nan
(context
)
714 return other
._fix
_nan
(context
)
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
725 Return 0 if neither operand is a NaN.
729 context
= getcontext()
731 if self
._is
_special
or other
._is
_special
:
733 return context
._raise
_error
(InvalidOperation
,
734 'comparison involving sNaN',
736 elif other
.is_snan():
737 return context
._raise
_error
(InvalidOperation
,
738 'comparison involving sNaN',
741 return context
._raise
_error
(InvalidOperation
,
742 'comparison involving NaN',
744 elif other
.is_qnan():
745 return context
._raise
_error
(InvalidOperation
,
746 'comparison involving NaN',
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
771 return -((-1)**other
._sign
)
773 return (-1)**self
._sign
775 # If different signs, neg one is less
776 if other
._sign
< self
._sign
:
778 if self
._sign
< other
._sign
:
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:
810 if self
.is_nan() or other
.is_nan():
812 return self
._cmp
(other
) == 0
814 def __ne__(self
, other
):
815 other
= _convert_other(other
)
816 if other
is NotImplemented:
818 if self
.is_nan() or other
.is_nan():
820 return self
._cmp
(other
) != 0
823 def __lt__(self
, other
, context
=None):
824 other
= _convert_other(other
)
825 if other
is NotImplemented:
827 ans
= self
._compare
_check
_nans
(other
, context
)
830 return self
._cmp
(other
) < 0
832 def __le__(self
, other
, context
=None):
833 other
= _convert_other(other
)
834 if other
is NotImplemented:
836 ans
= self
._compare
_check
_nans
(other
, context
)
839 return self
._cmp
(other
) <= 0
841 def __gt__(self
, other
, context
=None):
842 other
= _convert_other(other
)
843 if other
is NotImplemented:
845 ans
= self
._compare
_check
_nans
(other
, context
)
848 return self
._cmp
(other
) > 0
850 def __ge__(self
, other
, context
=None):
851 other
= _convert_other(other
)
852 if other
is NotImplemented:
854 ans
= self
._compare
_check
_nans
(other
, context
)
857 return self
._cmp
(other
) >= 0
859 def compare(self
, other
, context
=None):
860 """Compares one to another.
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
)
876 return Decimal(self
._cmp
(other
))
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')).
887 raise TypeError('Cannot hash a NaN value.')
888 return hash(str(self
))
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
904 return hash((self
._sign
,
905 self
._exp
+len(self
._int
),
906 self
._int
.rstrip('0')))
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
)
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
]
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
945 # usual scientific notation: 1 digit on left of the point
947 elif self
._int
== '0':
948 # engineering notation, zero
949 dotplace
= (leftdigits
+ 1) % 3 - 1
951 # engineering notation, nonzero
952 dotplace
= (leftdigits
- 1) % 3 + 1
956 fracpart
= '.' + '0'*(-dotplace
) + self
._int
957 elif dotplace
>= len(self
._int
):
958 intpart
= self
._int
+'0'*(dotplace
-len(self
._int
))
961 intpart
= self
._int
[:dotplace
]
962 fracpart
= '.' + self
._int
[dotplace
:]
963 if leftdigits
== dotplace
:
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.
988 ans
= self
._check
_nans
(context
=context
)
993 # -Decimal('0') is Decimal('0'), not Decimal('-0')
994 ans
= self
.copy_abs()
996 ans
= self
.copy_negate()
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
)
1014 ans
= self
.copy_abs()
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
1030 return self
.copy_abs()
1032 if self
._is
_special
:
1033 ans
= self
._check
_nans
(context
=context
)
1038 ans
= self
.__neg
__(context
=context
)
1040 ans
= self
.__pos
__(context
=context
)
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:
1054 context
= getcontext()
1056 if self
._is
_special
or other
._is
_special
:
1057 ans
= self
._check
_nans
(other
, context
)
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
)
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.
1075 if not self
and not other
:
1076 sign
= min(self
._sign
, other
._sign
)
1079 ans
= _dec_from_triple(sign
, '0', exp
)
1080 ans
= ans
._fix
(context
)
1083 exp
= max(exp
, other
._exp
- context
.prec
-1)
1084 ans
= other
._rescale
(exp
, context
.rounding
)
1085 ans
= ans
._fix
(context
)
1088 exp
= max(exp
, self
._exp
- context
.prec
-1)
1089 ans
= self
._rescale
(exp
, context
.rounding
)
1090 ans
= ans
._fix
(context
)
1093 op1
= _WorkRep(self
)
1094 op2
= _WorkRep(other
)
1095 op1
, op2
= _normalize(op1
, op2
, context
.prec
)
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
)
1104 if op1
.int < op2
.int:
1106 # OK, now abs(op1) > abs(op2)
1109 op1
.sign
, op2
.sign
= op2
.sign
, op1
.sign
1112 # So we know the sign, and op1 > 0.
1115 op1
.sign
, op2
.sign
= (0, 0)
1118 # Now, op1 > abs(op2) > 0
1121 result
.int = op1
.int + op2
.int
1123 result
.int = op1
.int - op2
.int
1125 result
.exp
= op1
.exp
1126 ans
= Decimal(result
)
1127 ans
= ans
._fix
(context
)
1132 def __sub__(self
, other
, context
=None):
1133 """Return self - other"""
1134 other
= _convert_other(other
)
1135 if other
is NotImplemented:
1138 if self
._is
_special
or other
._is
_special
:
1139 ans
= self
._check
_nans
(other
, context
=context
)
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:
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:
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
)
1173 if self
._isinfinity
():
1175 return context
._raise
_error
(InvalidOperation
, '(+-)INF * 0')
1176 return Infsign
[resultsign
]
1178 if other
._isinfinity
():
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
)
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
)
1197 if other
._int
== '1':
1198 ans
= _dec_from_triple(resultsign
, self
._int
, resultexp
)
1199 ans
= ans
._fix
(context
)
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
)
1211 def __truediv__(self
, other
, context
=None):
1212 """Return self / other."""
1213 other
= _convert_other(other
)
1214 if other
is NotImplemented:
1215 return NotImplemented
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
)
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
1240 return context
._raise
_error
(DivisionUndefined
, '0 / 0')
1241 return context
._raise
_error
(DivisionByZero
, 'x / 0', sign
)
1244 exp
= self
._exp
- other
._exp
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
)
1253 coeff
, remainder
= divmod(op1
.int * 10**shift
, op2
.int)
1255 coeff
, remainder
= divmod(op1
.int, op2
.int * 10**-shift
)
1257 # result is not exact; adjust to ensure correct rounding
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:
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
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
)
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')
1303 def __rtruediv__(self
, other
, context
=None):
1304 """Swaps self/other and returns __truediv__."""
1305 other
= _convert_other(other
)
1306 if other
is NotImplemented:
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:
1319 context
= getcontext()
1321 ans
= self
._check
_nans
(other
, context
)
1325 sign
= self
._sign ^ other
._sign
1326 if self
._isinfinity
():
1327 if other
._isinfinity
():
1328 ans
= context
._raise
_error
(InvalidOperation
, 'divmod(INF, INF)')
1331 return (Infsign
[sign
],
1332 context
._raise
_error
(InvalidOperation
, 'INF % x'))
1336 ans
= context
._raise
_error
(DivisionUndefined
, 'divmod(0, 0)')
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:
1351 return other
.__divmod
__(self
, context
=context
)
1353 def __mod__(self
, other
, context
=None):
1357 other
= _convert_other(other
)
1358 if other
is NotImplemented:
1362 context
= getcontext()
1364 ans
= self
._check
_nans
(other
, context
)
1368 if self
._isinfinity
():
1369 return context
._raise
_error
(InvalidOperation
, 'INF % x')
1372 return context
._raise
_error
(InvalidOperation
, 'x % 0')
1374 return context
._raise
_error
(DivisionUndefined
, '0 % 0')
1376 remainder
= self
._divide
(other
, context
)[1]
1377 remainder
= remainder
._fix
(context
)
1380 def __rmod__(self
, other
, context
=None):
1381 """Swaps self/other and returns __mod__."""
1382 other
= _convert_other(other
)
1383 if other
is NotImplemented:
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
1392 context
= getcontext()
1394 other
= _convert_other(other
, raiseit
=True)
1396 ans
= self
._check
_nans
(other
, context
)
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
1408 return context
._raise
_error
(InvalidOperation
,
1409 'remainder_near(x, 0)')
1411 return context
._raise
_error
(DivisionUndefined
,
1412 'remainder_near(0, 0)')
1414 # other = +/-infinity -> remainder = self
1415 if other
._isinfinity
():
1417 return ans
._fix
(context
)
1419 # self = 0 -> remainder = self, with ideal exponent
1420 ideal_exponent
= min(self
._exp
, other
._exp
)
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
)
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
)
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:
1450 if q
>= 10**context
.prec
:
1451 return context
._raise
_error
(DivisionImpossible
)
1453 # result has same sign as self unless r is negative
1459 ans
= _dec_from_triple(sign
, str(r
), ideal_exponent
)
1460 return ans
._fix
(context
)
1462 def __floordiv__(self
, other
, context
=None):
1464 other
= _convert_other(other
)
1465 if other
is NotImplemented:
1469 context
= getcontext()
1471 ans
= self
._check
_nans
(other
, context
)
1475 if self
._isinfinity
():
1476 if other
._isinfinity
():
1477 return context
._raise
_error
(InvalidOperation
, 'INF // INF')
1479 return Infsign
[self
._sign ^ other
._sign
]
1483 return context
._raise
_error
(DivisionByZero
, 'x // 0',
1484 self
._sign ^ other
._sign
)
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:
1495 return other
.__floordiv
__(self
, context
=context
)
1497 def __float__(self
):
1498 """Float representation."""
1499 return float(str(self
))
1502 """Converts self to an int, truncating if necessary."""
1503 if self
._is
_special
:
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
1511 return s
*int(self
._int
)*10**self
._exp
1513 return s
*int(self
._int
[:self
._exp
] or '0')
1525 def conjugate(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"""
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.
1549 self - Decimal instance
1550 context - context used.
1553 if self
._is
_special
:
1555 # decapitate payload if necessary
1556 return self
._fix
_nan
(context
)
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()
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
)
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
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
)
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
1592 self
= _dec_from_triple(self
._sign
, '1', exp_min
-1)
1594 this_function
= getattr(self
, self
._pick
_rounding
_function
[context
.rounding
])
1595 changed
= this_function(digits
)
1596 coeff
= self
._int
[:digits
] or '0'
1598 coeff
= str(int(coeff
)+1)
1599 ans
= _dec_from_triple(self
._sign
, coeff
, exp_min
)
1602 context
._raise
_error
(Inexact
)
1603 if self_is_subnormal
:
1604 context
._raise
_error
(Underflow
)
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
1612 ans
= _dec_from_triple(ans
._sign
,
1613 ans
._int
[:-1], ans
._exp
+1)
1615 # Inexact and Rounded have already been raised
1616 ans
= context
._raise
_error
(Overflow
, 'above Emax',
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
):
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':
1659 elif _all_zeros(self
._int
, prec
):
1664 def _round_half_down(self
, prec
):
1666 if _exact_half(self
._int
, prec
):
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'):
1677 return self
._round
_half
_up
(prec
)
1679 def _round_ceiling(self
, prec
):
1680 """Rounds up (not away from 0 if negative.)"""
1682 return self
._round
_down
(prec
)
1684 return -self
._round
_down
(prec
)
1687 return self
._round
_ceiling
(0)
1689 def _round_floor(self
, prec
):
1690 """Rounds down (not towards 0 if negative)"""
1692 return self
._round
_down
(prec
)
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
)
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
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
:
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':
1730 elif other
._exp
== 'n':
1732 elif self
._exp
== 'F':
1734 return context
._raise
_error
(InvalidOperation
,
1736 product
= Infsign
[self
._sign ^ other
._sign
]
1737 elif other
._exp
== 'F':
1739 return context
._raise
_error
(InvalidOperation
,
1741 product
= Infsign
[self
._sign ^ other
._sign
]
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)
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',
1771 if other_is_nan
== 2:
1772 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1774 if modulo_is_nan
== 2:
1775 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1778 return self
._fix
_nan
(context
)
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')
1791 return context
._raise
_error
(InvalidOperation
,
1792 'pow() 2nd argument cannot be '
1793 'negative when 3rd argument specified')
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 '
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
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 =
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
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
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|
1894 xc
, xe
= x
.int, x
.exp
1900 yc
, ye
= y
.int, y
.exp
1905 # case where xc == 1: result is 10**(xe*y), with xe*y
1906 # required to be an integer
1909 exponent
= xe
*yc
*10**ye
1911 exponent
, remainder
= divmod(xe
*yc
, 10**-ye
)
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)
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.
1927 last_digit
= xc
% 10
1928 if last_digit
in (2,4,6,8):
1929 # quick test for power of 2
1932 # now xc is a power of 2; e is its exponent
1934 # find e*y and xe*y; both must be integers
1936 y_as_int
= yc
*10**ye
1941 e
, remainder
= divmod(e
*yc
, ten_pow
)
1944 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1948 if e
*65 >= p
*93: # 93/65 > log(10)/log(5)
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
)
1963 y_as_integer
= yc
*10**ye
1965 xe
= xe
*y_as_integer
1968 e
, remainder
= divmod(e
*yc
, ten_pow
)
1971 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1974 if e
*3 >= p
*10: # 10/3 > log(10)/log(2)
1983 return _dec_from_triple(0, str(xc
), xe
)
1985 # now y is positive; find m and n such that y = m/n
1989 if xe
!= 0 and len(str(abs(yc
*xe
))) <= -ye
:
1991 xc_bits
= _nbits(xc
)
1992 if xc
!= 1 and len(str(abs(yc
)*xc_bits
)) <= -ye
:
1994 m
, n
= yc
, 10**(-ye
)
1995 while m
% 2 == n
% 2 == 0:
1998 while m
% 5 == n
% 5 == 0:
2002 # compute nth root of xc*10**xe
2004 # if 1 < xc < 2**n then xc isn't an nth power
2005 if xc
!= 1 and xc_bits
<= n
:
2008 xe
, rem
= divmod(xe
, n
)
2012 # compute nth root of xc using Newton's method
2013 a
= 1 << -(-_nbits(xc
)//n
) # initial estimate
2015 q
, r
= divmod(xc
, a
**(n
-1))
2019 a
= (a
*(n
-1) + q
)//n
2020 if not (a
== q
and r
== 0):
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
):
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
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
))
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
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
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:
2079 context
= getcontext()
2081 # either argument is a NaN => result is NaN
2082 ans
= self
._check
_nans
(other
, context
)
2086 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2089 return context
._raise
_error
(InvalidOperation
, '0 ** 0')
2093 # result has sign 1 iff self._sign is 1 and other is an odd integer
2096 if other
._isinteger
():
2097 if not other
._iseven
():
2100 # -ve**noninteger = NaN
2101 # (-0)**noninteger = 0**noninteger
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
2110 if other
._sign
== 0:
2111 return _dec_from_triple(result_sign
, '0', 0)
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
]
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
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:
2133 elif other
> context
.prec
:
2134 multiplier
= context
.prec
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
)
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)
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.
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
._log
10_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)
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
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))
2192 xc
, xe
= x
.int, x
.exp
2194 yc
, ye
= y
.int, y
.exp
2198 # compute correctly rounded result: start with precision +3,
2199 # then increase precision until result is unambiguously roundable
2202 coeff
, exp
= _dpower(xc
, xe
, yc
, ye
, p
+extra
)
2203 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
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
,
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
)
2229 def __rpow__(self
, other
, context
=None):
2230 """Swaps self/other and returns __pow__."""
2231 other
= _convert_other(other
)
2232 if other
is NotImplemented:
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"""
2240 context
= getcontext()
2242 if self
._is
_special
:
2243 ans
= self
._check
_nans
(context
=context
)
2247 dup
= self
._fix
(context
)
2248 if dup
._isinfinity
():
2252 return _dec_from_triple(dup
._sign
, '0', 0)
2253 exp_max
= [context
.Emax
, context
.Etop()][context
._clamp
]
2256 while dup
._int
[end
-1] == '0' and exp
< exp_max
:
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)
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
)
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
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
)
2291 context
._raise
_error
(Inexact
)
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')
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
)
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
)
2331 def same_quantum(self
, other
):
2332 """Return True if self and other have the same exponent; otherwise
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
2354 exp = exp to scale to (an integer)
2355 rounding = rounding mode
2357 if self
._is
_special
:
2358 return Decimal(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
2371 self
= _dec_from_triple(self
._sign
, '1', exp
-1)
2373 this_function
= getattr(self
, self
._pick
_rounding
_function
[rounding
])
2374 changed
= this_function(digits
)
2375 coeff
= self
._int
[:digits
] or '0'
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.
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
)
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
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
)
2417 return Decimal(self
)
2419 return Decimal(self
)
2421 return _dec_from_triple(self
._sign
, '0', 0)
2423 context
= getcontext()
2424 if rounding
is None:
2425 rounding
= context
.rounding
2426 context
._raise
_error
(Rounded
)
2427 ans
= self
._rescale
(0, rounding
)
2429 context
._raise
_error
(Inexact
)
2432 def to_integral_value(self
, rounding
=None, context
=None):
2433 """Rounds to the nearest integer, without raising inexact, rounded."""
2435 context
= getcontext()
2436 if rounding
is None:
2437 rounding
= context
.rounding
2438 if self
._is
_special
:
2439 ans
= self
._check
_nans
(context
=context
)
2442 return Decimal(self
)
2444 return Decimal(self
)
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."""
2454 context
= getcontext()
2456 if self
._is
_special
:
2457 ans
= self
._check
_nans
(context
=context
)
2461 if self
._isinfinity
() and self
._sign
== 0:
2462 return Decimal(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
)
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.
2502 l
= (len(self
._int
) >> 1) + 1
2505 l
= len(self
._int
)+1 >> 1
2507 # rescale so that c has exactly prec base 100 'digits'
2513 c
, remainder
= divmod(c
, 100**-shift
)
2514 exact
= not remainder
2517 # find n = floor(sqrt(c)) using Newton's method
2525 exact
= exact
and n
*n
== c
2528 # result is exact; rescale to use ideal exponent e
2530 # assert n % 10**shift == 0
2536 # result is not exact; fix last digit as described above
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
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)
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
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
)
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
)
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)
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
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
)
2617 c
= self
.compare_total(other
)
2624 return ans
._fix
(context
)
2626 def _isinteger(self
):
2627 """Returns whether self is an integer"""
2628 if self
._is
_special
:
2632 rest
= self
._int
[self
._exp
:]
2633 return rest
== '0'*len(rest
)
2636 """Returns True if self is even. Assumes self is an integer."""
2637 if not self
or self
._exp
> 0:
2639 return self
._int
[-1+self
._exp
] in '02468'
2642 """Return the adjusted exponent of self"""
2644 return self
._exp
+ len(self
._int
) - 1
2645 # If NaN or Infinity, self._exp is string
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.
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
)
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
2676 # if one is negative and the other is positive, it's easy
2677 if self
._sign
and not other
._sign
:
2679 if not self
._sign
and other
._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
:
2693 if self
._int
> other
._int
:
2724 if self
._exp
< other
._exp
:
2729 if self
._exp
> other
._exp
:
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.
2743 o
= other
.copy_abs()
2744 return s
.compare_total(o
)
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."""
2753 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
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."""
2766 context
= getcontext()
2769 ans
= self
._check
_nans
(context
=context
)
2773 # exp(-Infinity) = 0
2774 if self
._isinfinity
() == -1:
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.
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)):
2799 ans
= _dec_from_triple(0, '1', context
.Emax
+1)
2800 elif self
._sign
== 1 and adj
> len(str((-context
.Etiny()+1)*3)):
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)
2812 c
, e
= op
.int, op
.exp
2816 # compute correctly rounded result: increase precision by
2817 # 3 digits at a time until we get an unambiguously
2821 coeff
, exp
= _dexp(c
, e
, p
+extra
)
2822 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
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
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.
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
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'
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
:
2866 context
= getcontext()
2867 return context
.Emin
<= self
.adjusted() <= context
.Emax
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
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
:
2886 context
= getcontext()
2887 return self
.adjusted() < context
.Emin
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
2902 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2903 return len(str(adj
*23//10)) - 1
2906 return len(str((-1-adj
)*23//10)) - 1
2908 c
, e
= op
.int, op
.exp
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."""
2922 context
= getcontext()
2925 ans
= self
._check
_nans
(context
=context
)
2929 # ln(0.0) == -Infinity
2933 # ln(Infinity) = Infinity
2934 if self
._isinfinity
() == 1:
2941 # ln(negative) raises InvalidOperation
2943 return context
._raise
_error
(InvalidOperation
,
2944 'ln of a negative value')
2946 # result is irrational, so necessarily inexact
2948 c
, e
= op
.int, op
.exp
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
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)):
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
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
2983 return len(str(adj
))-1
2986 return len(str(-1-adj
))-1
2988 c
, e
= op
.int, op
.exp
2993 return len(num
) - len(den
) - (num
< den
) + 2
2994 # adj == -1, 0.1 <= self < 1
2996 return len(num
) + e
- (num
< "231") - 1
2998 def log10(self
, context
=None):
2999 """Returns the base 10 logarithm of self."""
3002 context
= getcontext()
3005 ans
= self
._check
_nans
(context
=context
)
3009 # log10(0.0) == -Infinity
3013 # log10(Infinity) = Infinity
3014 if self
._isinfinity
() == 1:
3017 # log10(negative or -Infinity) raises InvalidOperation
3019 return context
._raise
_error
(InvalidOperation
,
3020 'log10 of a negative value')
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)
3027 # result is irrational, so necessarily inexact
3029 c
, e
= op
.int, op
.exp
3032 # correctly rounded result: repeatedly increase precision
3033 # until result is unambiguously roundable
3034 places
= p
-self
._log
10_exp
_bound
()+2
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)):
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
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).
3058 ans
= self
._check
_nans
(context
=context
)
3063 context
= getcontext()
3065 # logb(+/-Inf) = +Inf
3066 if self
._isinfinity
():
3069 # logb(0) = -Inf, DivisionByZero
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
3085 if self
._sign
!= 0 or self
._exp
!= 0:
3087 for dig
in self
._int
:
3092 def _fill_logical(self
, context
, opa
, opb
):
3093 dif
= context
.prec
- len(opa
)
3097 opa
= opa
[-context
.prec
:]
3098 dif
= context
.prec
- len(opb
)
3102 opb
= opb
[-context
.prec
:]
3105 def logical_and(self
, other
, context
=None):
3106 """Applies an 'and' operation between self and other's digits."""
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."""
3122 context
= getcontext()
3123 return self
.logical_xor(_dec_from_triple(0,'1'*context
.prec
,0),
3126 def logical_or(self
, other
, context
=None):
3127 """Applies an 'or' operation between self and other's digits."""
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."""
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)
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
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())
3175 c
= self
.compare_total(other
)
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)
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
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())
3205 c
= self
.compare_total(other
)
3212 return ans
._fix
(context
)
3214 def next_minus(self
, context
=None):
3215 """Returns the largest representable number smaller than itself."""
3217 context
= getcontext()
3219 ans
= self
._check
_nans
(context
=context
)
3223 if self
._isinfinity
() == -1:
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
:
3234 return self
.__sub
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3237 def next_plus(self
, context
=None):
3238 """Returns the smallest representable number larger than itself."""
3240 context
= getcontext()
3242 ans
= self
._check
_nans
(context
=context
)
3246 if self
._isinfinity
() == 1:
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
:
3257 return self
.__add
__(_dec_from_triple(0, '1', context
.Etiny()-1),
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)
3272 context
= getcontext()
3274 ans
= self
._check
_nans
(other
, context
)
3278 comparison
= self
._cmp
(other
)
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',
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
3302 context
._raise
_error
(Clamped
)
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:
3325 inf
= self
._isinfinity
()
3336 context
= getcontext()
3337 if self
.is_subnormal(context
=context
):
3342 # just a normal, regular, boring number, :)
3349 """Just returns 10, as this is Decimal, :)"""
3352 def rotate(self
, other
, context
=None):
3353 """Returns a rotated copy of self, value-of-other times."""
3355 context
= getcontext()
3357 ans
= self
._check
_nans
(other
, context
)
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
3372 topad
= context
.prec
- len(rotdig
)
3374 rotdig
= '0'*topad
+ rotdig
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."""
3384 context
= getcontext()
3386 ans
= self
._check
_nans
(other
, context
)
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
))
3404 def shift(self
, other
, context
=None):
3405 """Returns a shifted copy of self, value-of-other times."""
3407 context
= getcontext()
3409 ans
= self
._check
_nans
(other
, context
)
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
3424 return Decimal(self
)
3426 topad
= context
.prec
- len(rotdig
)
3428 rotdig
= '0'*topad
+ rotdig
3432 rotated
= rotdig
[:torot
]
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
),))
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).
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
3514 elif spec
['type'] in 'gG':
3515 if self
._exp
<= 0 and leftdigits
> -6:
3516 dotplace
= leftdigits
3520 # figure out main part of numeric string...
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
))
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'] == '%':
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
3548 This function is for *internal use only*.
3551 self
= object.__new
__(Decimal
)
3553 self
._int
= coefficient
3554 self
._exp
= exponent
3555 self
._is
_special
= special
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.
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
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):
3614 if _ignored_flags
is None:
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():
3622 setattr(self
, name
, _copy
.copy(getattr(DefaultContext
, name
)))
3624 setattr(self
, name
, val
)
3628 """Show the current context."""
3630 s
.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3631 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
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
)
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
)
3659 def _raise_error(self
, condition
, explanation
= None, *args
):
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
3689 self
._ignored
_flags
= (self
._ignored
_flags
+ 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)):
3697 self
._ignored
_flags
.remove(flag
)
3700 """A Context cannot be hashed."""
3701 # We inherit object.__hash__, so we must deny this explicitly
3702 raise TypeError("Cannot hash a Context.")
3705 """Returns Etiny (= Emin - prec + 1)"""
3706 return int(self
.Emin
- self
.prec
+ 1)
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
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 "
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")
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'))
3758 >>> ExtendedContext.abs(Decimal('-100'))
3760 >>> ExtendedContext.abs(Decimal('101.5'))
3762 >>> ExtendedContext.abs(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'))
3772 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+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'))
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
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'))
3807 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3809 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3811 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3813 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3815 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.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'))
3829 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3831 >>> c.flags[InvalidOperation] = 0
3832 >>> print(c.flags[InvalidOperation])
3834 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3836 >>> print(c.flags[InvalidOperation])
3838 >>> c.flags[InvalidOperation] = 0
3839 >>> print(c.flags[InvalidOperation])
3841 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
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
3855 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3857 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3859 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3861 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3863 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3865 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
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'))
3882 >>> ExtendedContext.copy_abs(Decimal('-100'))
3887 def copy_decimal(self
, a
):
3888 """Returns a copy of the decimal objet.
3890 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3892 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3897 def copy_negate(self
, a
):
3898 """Returns a copy of the operand with the sign inverted.
3900 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3902 >>> ExtendedContext.copy_negate(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'))
3915 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3917 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3919 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
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'))
3933 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3935 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3937 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3939 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3941 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3943 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3945 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
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'))
3955 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3957 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3960 return a
.__floordiv
__(b
, context
=self
)
3962 def divmod(self
, a
, b
):
3963 return a
.__divmod
__(b
, context
=self
)
3968 >>> c = ExtendedContext.copy()
3971 >>> c.exp(Decimal('-Infinity'))
3973 >>> c.exp(Decimal('-1'))
3974 Decimal('0.367879441')
3975 >>> c.exp(Decimal('0'))
3977 >>> c.exp(Decimal('1'))
3978 Decimal('2.71828183')
3979 >>> c.exp(Decimal('0.693147181'))
3980 Decimal('2.00000000')
3981 >>> c.exp(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'))
3995 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
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'))
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
4019 >>> ExtendedContext.is_finite(Decimal('2.50'))
4021 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4023 >>> ExtendedContext.is_finite(Decimal('0'))
4025 >>> ExtendedContext.is_finite(Decimal('Inf'))
4027 >>> ExtendedContext.is_finite(Decimal('NaN'))
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'))
4037 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4039 >>> ExtendedContext.is_infinite(Decimal('NaN'))
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'))
4050 >>> ExtendedContext.is_nan(Decimal('NaN'))
4052 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4057 def is_normal(self
, a
):
4058 """Return True if the operand is a normal number;
4059 otherwise return False.
4061 >>> c = ExtendedContext.copy()
4064 >>> c.is_normal(Decimal('2.50'))
4066 >>> c.is_normal(Decimal('0.1E-999'))
4068 >>> c.is_normal(Decimal('0.00'))
4070 >>> c.is_normal(Decimal('-Inf'))
4072 >>> c.is_normal(Decimal('NaN'))
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'))
4082 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4084 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4089 def is_signed(self
, a
):
4090 """Return True if the operand is negative; otherwise return False.
4092 >>> ExtendedContext.is_signed(Decimal('2.50'))
4094 >>> ExtendedContext.is_signed(Decimal('-12'))
4096 >>> ExtendedContext.is_signed(Decimal('-0'))
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'))
4107 >>> ExtendedContext.is_snan(Decimal('NaN'))
4109 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4114 def is_subnormal(self
, a
):
4115 """Return True if the operand is subnormal; otherwise return False.
4117 >>> c = ExtendedContext.copy()
4120 >>> c.is_subnormal(Decimal('2.50'))
4122 >>> c.is_subnormal(Decimal('0.1E-999'))
4124 >>> c.is_subnormal(Decimal('0.00'))
4126 >>> c.is_subnormal(Decimal('-Inf'))
4128 >>> c.is_subnormal(Decimal('NaN'))
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'))
4138 >>> ExtendedContext.is_zero(Decimal('2.50'))
4140 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4146 """Returns the natural (base e) logarithm of the operand.
4148 >>> c = ExtendedContext.copy()
4151 >>> c.ln(Decimal('0'))
4152 Decimal('-Infinity')
4153 >>> c.ln(Decimal('1.000'))
4155 >>> c.ln(Decimal('2.71828183'))
4156 Decimal('1.00000000')
4157 >>> c.ln(Decimal('10'))
4158 Decimal('2.30258509')
4159 >>> c.ln(Decimal('+Infinity'))
4162 return a
.ln(context
=self
)
4165 """Returns the base 10 logarithm of the operand.
4167 >>> c = ExtendedContext.copy()
4170 >>> c.log10(Decimal('0'))
4171 Decimal('-Infinity')
4172 >>> c.log10(Decimal('0.001'))
4174 >>> c.log10(Decimal('1.000'))
4176 >>> c.log10(Decimal('2'))
4177 Decimal('0.301029996')
4178 >>> c.log10(Decimal('10'))
4180 >>> c.log10(Decimal('70'))
4181 Decimal('1.84509804')
4182 >>> c.log10(Decimal('+Infinity'))
4185 return a
.log10(context
=self
)
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'))
4197 >>> ExtendedContext.logb(Decimal('2.50'))
4199 >>> ExtendedContext.logb(Decimal('0.03'))
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'))
4213 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4215 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4217 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4219 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4221 >>> ExtendedContext.logical_and(Decimal('1111'), 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'))
4237 >>> ExtendedContext.logical_invert(Decimal('101010101'))
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'))
4249 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4251 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4253 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4255 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4257 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
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'))
4269 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4271 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4273 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4275 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4277 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4280 return a
.logical_xor(b
, context
=self
)
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'))
4293 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4295 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4297 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
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
)
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'))
4317 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4319 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4321 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
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
)
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'))
4339 >>> ExtendedContext.minus(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'))
4354 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4356 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4358 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-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()
4371 >>> ExtendedContext.next_minus(Decimal('1'))
4372 Decimal('0.999999999')
4373 >>> c.next_minus(Decimal('1E-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()
4388 >>> ExtendedContext.next_plus(Decimal('1'))
4389 Decimal('1.00000001')
4390 >>> c.next_plus(Decimal('-1E-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
4407 >>> c = ExtendedContext.copy()
4410 >>> c.next_toward(Decimal('1'), Decimal('2'))
4411 Decimal('1.00000001')
4412 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
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'))
4420 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4421 Decimal('-1.00000004')
4422 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
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
4433 >>> ExtendedContext.normalize(Decimal('2.1'))
4435 >>> ExtendedContext.normalize(Decimal('-2.0'))
4437 >>> ExtendedContext.normalize(Decimal('1.200'))
4439 >>> ExtendedContext.normalize(Decimal('-120'))
4441 >>> ExtendedContext.normalize(Decimal('120.00'))
4443 >>> ExtendedContext.normalize(Decimal('0.00'))
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:
4463 >>> c = Context(ExtendedContext)
4466 >>> c.number_class(Decimal('Infinity'))
4468 >>> c.number_class(Decimal('1E-10'))
4470 >>> c.number_class(Decimal('2.50'))
4472 >>> c.number_class(Decimal('0.1E-999'))
4474 >>> c.number_class(Decimal('0'))
4476 >>> c.number_class(Decimal('-0'))
4478 >>> c.number_class(Decimal('-0.1E-999'))
4480 >>> c.number_class(Decimal('-1E-10'))
4482 >>> c.number_class(Decimal('-2.50'))
4484 >>> c.number_class(Decimal('-Infinity'))
4486 >>> c.number_class(Decimal('NaN'))
4488 >>> c.number_class(Decimal('-NaN'))
4490 >>> c.number_class(Decimal('sNaN'))
4493 return a
.number_class(context
=self
)
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'))
4504 >>> ExtendedContext.plus(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
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
4531 >>> c = ExtendedContext.copy()
4534 >>> c.power(Decimal('2'), Decimal('3'))
4536 >>> c.power(Decimal('-2'), Decimal('3'))
4538 >>> c.power(Decimal('2'), Decimal('-3'))
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'))
4546 >>> c.power(Decimal('Infinity'), Decimal('0'))
4548 >>> c.power(Decimal('Infinity'), Decimal('1'))
4550 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4552 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4554 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4555 Decimal('-Infinity')
4556 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4558 >>> c.power(Decimal('0'), Decimal('0'))
4561 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4563 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4565 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4567 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4569 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4571 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4573 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
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'))
4598 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4600 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4602 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4604 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4606 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4607 Decimal('-Infinity')
4608 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4610 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4612 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4614 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4616 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4618 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4620 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4622 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4624 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4627 return a
.quantize(b
, context
=self
)
4630 """Just returns 10, as this is Decimal, :)
4632 >>> ExtendedContext.radix()
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'))
4651 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4653 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4655 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4657 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4659 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
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
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'))
4676 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4678 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4680 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4682 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4684 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4686 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.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'))
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
4719 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4721 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4723 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4725 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
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'))
4735 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4737 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('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'))
4756 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
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
)
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
4771 >>> ExtendedContext.sqrt(Decimal('0'))
4773 >>> ExtendedContext.sqrt(Decimal('-0'))
4775 >>> ExtendedContext.sqrt(Decimal('0.39'))
4776 Decimal('0.624499800')
4777 >>> ExtendedContext.sqrt(Decimal('100'))
4779 >>> ExtendedContext.sqrt(Decimal('1'))
4781 >>> ExtendedContext.sqrt(Decimal('1.0'))
4783 >>> ExtendedContext.sqrt(Decimal('1.00'))
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'))
4799 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4801 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
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
4830 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4832 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4834 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4836 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4838 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4840 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4842 >>> ExtendedContext.to_integral_exact(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'))
4860 >>> ExtendedContext.to_integral_value(Decimal('100'))
4862 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4864 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4866 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4868 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4870 >>> ExtendedContext.to_integral_value(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')
4884 # exp: None, int, or string
4886 def __init__(self
, value
=None):
4891 elif isinstance(value
, Decimal
):
4892 self
.sign
= value
._sign
4893 self
.int = int(value
._int
)
4894 self
.exp
= value
._exp
4896 # assert isinstance(value, tuple)
4897 self
.sign
= value
[0]
4902 return "(%r, %r, %r)" % (self
.sign
, self
.int, self
.exp
)
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
:
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
:
4932 tmp
.int *= 10 ** (tmp
.exp
- other
.exp
)
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,
4952 raise ValueError("The argument to _nbits should be nonnegative.")
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.")
4968 b
, a
= a
, a
--n
//a
>>1
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.
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
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
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
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.
5018 # argument reduction; R = number of reductions performed
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
))
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
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
5049 f
= e
+l
- (e
+l
>= 1)
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
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)
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.
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).
5082 f
= e
+l
- (e
+l
>= 1)
5084 # compute approximation to 10**p*log(d), with error < 27
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
5095 # p <= 0: just approximate the whole thing by 0; error < 2.31
5098 # compute approximation to f*10**p*log(10), with error < 11.
5100 extra
= len(str(abs(f
)))-1
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
)
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__."""
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).
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
5137 # compute p+extra digits, correct to within 1ulp
5139 digits
= str(_div_nearest(_ilog(10*M
, M
), 100))
5140 if digits
[-extra
:] != '0'*extra
:
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
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
)
5177 for i
in range(T
-1, 0, -1):
5178 y
= _div_nearest(x
*(Mshift
+ y
), Mshift
* i
)
5181 for k
in range(R
-1, -1, -1):
5183 y
= _div_nearest(y
*(y
+Mshift
), Mshift
)
5188 """Compute an approximation to exp(c*10**e), with p decimal places of
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
5204 # compute log(10) with extra precision = adjusted exponent of c*10**e
5205 extra
= max(0, e
+ len(str(c
)) - 1)
5208 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5212 cshift
= c
*10**shift
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)
5247 pc
= lxc
*yc
*10**shift
5249 pc
= _div_nearest(lxc
*yc
, 10**-shift
)
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
5257 coeff
, exp
= 10**p
-1, -p
5259 coeff
, exp
= _dexp(pc
, -(p
+1), p
+1)
5260 coeff
= _div_nearest(coeff
, 10)
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."""
5270 raise ValueError("The argument to _log10_lb should be nonnegative.")
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
):
5283 if isinstance(other
, int):
5284 return Decimal(other
)
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
],
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
5308 BasicContext
= Context(
5309 prec
=9, rounding
=ROUND_HALF_UP
,
5310 traps
=[DivisionByZero
, Overflow
, InvalidOperation
, Clamped
, Underflow
],
5314 ExtendedContext
= Context(
5315 prec
=9, rounding
=ROUND_HALF_EVEN
,
5321 ##### crud for parsing strings #############################################
5323 # Regular expression used for parsing numeric strings. Additional
5326 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5327 # whitespace. But note that the specification disallows whitespace in
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].
5339 _parser
= re
.compile(r
""" # A numeric string consists of:
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)
5352 (?P<diag>\d*) # with (possibly empty) diagnostic information.
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
5378 (?P<minimumwidth>(?!0)\d+)?
5379 (?:\.(?P<precision>0|(?!0)\d+))?
5380 (?P<type>[eEfFgG%])?
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
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
)
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
)
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
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 '-+':
5464 if spec_dict
['sign'] in ' +':
5465 sign
= spec_dict
['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']
5476 result
= padding
+ sign
+ body
5478 result
= sign
+ body
+ padding
5480 result
= sign
+ padding
+ body
5482 half
= len(padding
)//2
5483 result
= padding
[:half
] + sign
+ body
+ padding
[half
:]
5487 ##### Useful Constants (internal use only) ################################
5490 Inf
= Decimal('Inf')
5491 negInf
= Decimal('-Inf')
5492 NaN
= Decimal('NaN')
5495 Dec_n1
= Decimal(-1)
5497 # Infsign[sign] is infinity w/ that sign
5498 Infsign
= (Inf
, negInf
)
5502 if __name__
== '__main__':
5504 doctest
.testmod(sys
.modules
[__name__
])