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):
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 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'
140 from collections
import namedtuple
as _namedtuple
141 DecimalTuple
= _namedtuple('DecimalTuple', 'sign digits exponent')
143 DecimalTuple
= lambda *args
: args
146 ROUND_DOWN
= 'ROUND_DOWN'
147 ROUND_HALF_UP
= 'ROUND_HALF_UP'
148 ROUND_HALF_EVEN
= 'ROUND_HALF_EVEN'
149 ROUND_CEILING
= 'ROUND_CEILING'
150 ROUND_FLOOR
= 'ROUND_FLOOR'
151 ROUND_UP
= 'ROUND_UP'
152 ROUND_HALF_DOWN
= 'ROUND_HALF_DOWN'
153 ROUND_05UP
= 'ROUND_05UP'
157 class DecimalException(ArithmeticError):
158 """Base exception class.
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
176 def handle(self
, context
, *args
):
180 class Clamped(DecimalException
):
181 """Exponent of a 0 changed to fit bounds.
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
192 class InvalidOperation(DecimalException
):
193 """An invalid operation was performed.
195 Various bad things cause this:
197 Something creates a signaling NaN
203 x._rescale( non-integer )
208 An operand is invalid
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
215 def handle(self
, context
, *args
):
217 ans
= _dec_from_triple(args
[0]._sign
, args
[0]._int
, 'n', True)
218 return ans
._fix
_nan
(context
)
221 class ConversionSyntax(InvalidOperation
):
222 """Trying to convert badly formed string.
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
226 syntax. The result is [0,qNaN].
228 def handle(self
, context
, *args
):
231 class DivisionByZero(DecimalException
, ZeroDivisionError):
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
244 def handle(self
, context
, sign
, *args
):
247 class DivisionImpossible(InvalidOperation
):
248 """Cannot perform the division adequately.
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
252 longer than precision). The result is [0,qNaN].
255 def handle(self
, context
, *args
):
258 class DivisionUndefined(InvalidOperation
, ZeroDivisionError):
259 """Undefined result of division.
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
263 the dividend is also zero. The result is [0,qNaN].
266 def handle(self
, context
, *args
):
269 class Inexact(DecimalException
):
270 """Had to round, losing information.
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
274 were non-zero), or if an overflow or underflow condition occurs. The
275 result in all cases is unchanged.
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
281 class InvalidContext(InvalidOperation
):
282 """Invalid context. Unknown rounding, for example.
284 This occurs and signals invalid-operation if an invalid context was
285 detected during an operation. This can occur if contexts are not checked
286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
292 def handle(self
, context
, *args
):
295 class Rounded(DecimalException
):
296 """Number got rounded (not necessarily changed during rounding).
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
300 coefficient), or if an overflow or underflow condition occurs. The
301 result in all cases is unchanged.
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
307 class Subnormal(DecimalException
):
308 """Exponent < Emin before rounding.
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
312 Emin, before any rounding). The result in all cases is unchanged.
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
318 class Overflow(Inexact
, Rounded
):
319 """Numerical overflow.
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
326 The result depends on the rounding mode:
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
330 where sign is the sign of the intermediate result. For round-down, the
331 result is the largest finite number that can be represented in the
332 current precision, with the sign of the intermediate result. For
333 round-ceiling, the result is the same as for round-down if the sign of
334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
335 the result is the same as for round-down if the sign of the intermediate
336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
340 def handle(self
, context
, sign
, *args
):
341 if context
.rounding
in (ROUND_HALF_UP
, ROUND_HALF_EVEN
,
342 ROUND_HALF_DOWN
, ROUND_UP
):
345 if context
.rounding
== ROUND_CEILING
:
347 return _dec_from_triple(sign
, '9'*context
.prec
,
348 context
.Emax
-context
.prec
+1)
350 if context
.rounding
== ROUND_FLOOR
:
352 return _dec_from_triple(sign
, '9'*context
.prec
,
353 context
.Emax
-context
.prec
+1)
356 class Underflow(Inexact
, Rounded
, Subnormal
):
357 """Numerical underflow with result rounded to 0.
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
362 Emin). That is, the result is both inexact and subnormal.
364 The result after an underflow will be a subnormal number rounded, if
365 necessary, so that its exponent is not less than Etiny. This may result
366 in 0 with the sign of the intermediate result and an exponent of Etiny.
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 # List of public traps and flags
372 _signals
= [Clamped
, DivisionByZero
, Inexact
, Overflow
, Rounded
,
373 Underflow
, InvalidOperation
, Subnormal
]
375 # Map conditions (per the spec) to signals
376 _condition_map
= {ConversionSyntax
:InvalidOperation
,
377 DivisionImpossible
:InvalidOperation
,
378 DivisionUndefined
:InvalidOperation
,
379 InvalidContext
:InvalidOperation
}
381 ##### Context Functions ##################################################
383 # The getcontext() and setcontext() function manage access to a thread-local
384 # current context. Py2.4 offers direct support for thread locals. If that
385 # is not available, use threading.currentThread() which is slower but will
386 # work for older Pythons. If threads are not part of the build, create a
387 # mock threading object with threading.local() returning the module namespace.
392 # Python was compiled without threads; create a mock object instead
394 class MockThreading(object):
395 def local(self
, sys
=sys
):
396 return sys
.modules
[__name__
]
397 threading
= MockThreading()
398 del sys
, MockThreading
403 except AttributeError:
405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
407 if hasattr(threading
.currentThread(), '__decimal_context__'):
408 del threading
.currentThread().__decimal
_context
__
410 def setcontext(context
):
411 """Set this thread's context to context."""
412 if context
in (DefaultContext
, BasicContext
, ExtendedContext
):
413 context
= context
.copy()
414 context
.clear_flags()
415 threading
.currentThread().__decimal
_context
__ = context
418 """Returns this thread's context.
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
425 return threading
.currentThread().__decimal
_context
__
426 except AttributeError:
428 threading
.currentThread().__decimal
_context
__ = context
433 local
= threading
.local()
434 if hasattr(local
, '__decimal_context__'):
435 del local
.__decimal
_context
__
437 def getcontext(_local
=local
):
438 """Returns this thread's context.
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
445 return _local
.__decimal
_context
__
446 except AttributeError:
448 _local
.__decimal
_context
__ = context
451 def setcontext(context
, _local
=local
):
452 """Set this thread's context to context."""
453 if context
in (DefaultContext
, BasicContext
, ExtendedContext
):
454 context
= context
.copy()
455 context
.clear_flags()
456 _local
.__decimal
_context
__ = context
458 del threading
, local
# Don't contaminate the namespace
460 def localcontext(ctx
=None):
461 """Return a context manager for a copy of the supplied context
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
467 with localcontext() as ctx:
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
471 return +s # Convert result to normal precision
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
478 return +s # Convert result to normal context
480 >>> setcontext(DefaultContext)
481 >>> print getcontext().prec
483 >>> with localcontext():
484 ... ctx = getcontext()
489 >>> with localcontext(ExtendedContext):
490 ... print getcontext().prec
493 >>> print getcontext().prec
496 if ctx
is None: ctx
= getcontext()
497 return _ContextManager(ctx
)
500 ##### Decimal class #######################################################
502 class Decimal(object):
503 """Floating point class for decimal arithmetic."""
505 __slots__
= ('_exp','_int','_sign', '_is_special')
506 # Generally, the value of the Decimal instance is given by
507 # (-1)**_sign * _int * 10**_exp
508 # Special values are signified by _is_special == True
510 # We're immutable, so use __new__ not __init__
511 def __new__(cls
, value
="0", context
=None):
512 """Create a decimal point instance.
514 >>> Decimal('3.14') # string input
516 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
518 >>> Decimal(314) # int or long
520 >>> Decimal(Decimal(314)) # another decimal instance
522 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
526 # Note that the coefficient, self._int, is actually stored as
527 # a string rather than as a tuple of digits. This speeds up
528 # the "digits to integer" and "integer to digits" conversions
529 # that are used in almost every arithmetic operation on
530 # Decimals. This is an internal detail: the as_tuple function
531 # and the Decimal constructor still deal with tuples of
534 self
= object.__new
__(cls
)
537 # REs insist on real strings, so we can too.
538 if isinstance(value
, basestring
):
539 m
= _parser(value
.strip())
542 context
= getcontext()
543 return context
._raise
_error
(ConversionSyntax
,
544 "Invalid literal for Decimal: %r" % value
)
546 if m
.group('sign') == "-":
550 intpart
= m
.group('int')
551 if intpart
is not None:
553 fracpart
= m
.group('frac')
554 exp
= int(m
.group('exp') or '0')
555 if fracpart
is not None:
556 self
._int
= str((intpart
+fracpart
).lstrip('0') or '0')
557 self
._exp
= exp
- len(fracpart
)
559 self
._int
= str(intpart
.lstrip('0') or '0')
561 self
._is
_special
= False
563 diag
= m
.group('diag')
566 self
._int
= str(diag
.lstrip('0'))
567 if m
.group('signal'):
575 self
._is
_special
= True
579 if isinstance(value
, (int,long)):
585 self
._int
= str(abs(value
))
586 self
._is
_special
= False
589 # From another decimal
590 if isinstance(value
, Decimal
):
591 self
._exp
= value
._exp
592 self
._sign
= value
._sign
593 self
._int
= value
._int
594 self
._is
_special
= value
._is
_special
597 # From an internal working value
598 if isinstance(value
, _WorkRep
):
599 self
._sign
= value
.sign
600 self
._int
= str(value
.int)
601 self
._exp
= int(value
.exp
)
602 self
._is
_special
= False
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value
, (list,tuple)):
608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value
[0], (int, long)) and value
[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
616 self
._sign
= value
[0]
618 # infinity: value[1] is ignored
621 self
._is
_special
= True
623 # process and validate the digits in value[1]
625 for digit
in value
[1]:
626 if isinstance(digit
, (int, long)) and 0 <= digit
<= 9:
628 if digits
or digit
!= 0:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
634 if value
[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
636 self
._int
= ''.join(map(str, digits
))
638 self
._is
_special
= True
639 elif isinstance(value
[2], (int, long)):
640 # finite number: digits give the coefficient
641 self
._int
= ''.join(map(str, digits
or [0]))
643 self
._is
_special
= False
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
650 if isinstance(value
, float):
651 raise TypeError("Cannot convert float to Decimal. " +
652 "First convert the float to a string")
654 raise TypeError("Cannot convert %r to Decimal" % value
)
657 """Returns whether the number is not actually one.
671 def _isinfinity(self
):
672 """Returns whether the number is infinite
674 0 if finite or not a number
684 def _check_nans(self
, other
=None, context
=None):
685 """Returns whether the number is not actually one.
687 if self, other are sNaN, signal
688 if self, other are NaN return nan
691 Done before operations.
694 self_is_nan
= self
._isnan
()
698 other_is_nan
= other
._isnan
()
700 if self_is_nan
or other_is_nan
:
702 context
= getcontext()
705 return context
._raise
_error
(InvalidOperation
, 'sNaN',
707 if other_is_nan
== 2:
708 return context
._raise
_error
(InvalidOperation
, 'sNaN',
711 return self
._fix
_nan
(context
)
713 return other
._fix
_nan
(context
)
716 def _compare_check_nans(self
, other
, context
):
717 """Version of _check_nans used for the signaling comparisons
718 compare_signal, __le__, __lt__, __ge__, __gt__.
720 Signal InvalidOperation if either self or other is a (quiet
721 or signaling) NaN. Signaling NaNs take precedence over quiet
724 Return 0 if neither operand is a NaN.
728 context
= getcontext()
730 if self
._is
_special
or other
._is
_special
:
732 return context
._raise
_error
(InvalidOperation
,
733 'comparison involving sNaN',
735 elif other
.is_snan():
736 return context
._raise
_error
(InvalidOperation
,
737 'comparison involving sNaN',
740 return context
._raise
_error
(InvalidOperation
,
741 'comparison involving NaN',
743 elif other
.is_qnan():
744 return context
._raise
_error
(InvalidOperation
,
745 'comparison involving NaN',
749 def __nonzero__(self
):
750 """Return True if self is nonzero; otherwise return False.
752 NaNs and infinities are considered nonzero.
754 return self
._is
_special
or self
._int
!= '0'
756 def _cmp(self
, other
):
757 """Compare the two non-NaN decimal instances self and other.
759 Returns -1 if self < other, 0 if self == other and 1
760 if self > other. This routine is for internal use only."""
762 if self
._is
_special
or other
._is
_special
:
763 return cmp(self
._isinfinity
(), other
._isinfinity
())
765 # check for zeros; note that cmp(0, -0) should return 0
770 return -((-1)**other
._sign
)
772 return (-1)**self
._sign
774 # If different signs, neg one is less
775 if other
._sign
< self
._sign
:
777 if self
._sign
< other
._sign
:
780 self_adjusted
= self
.adjusted()
781 other_adjusted
= other
.adjusted()
782 if self_adjusted
== other_adjusted
:
783 self_padded
= self
._int
+ '0'*(self
._exp
- other
._exp
)
784 other_padded
= other
._int
+ '0'*(other
._exp
- self
._exp
)
785 return cmp(self_padded
, other_padded
) * (-1)**self
._sign
786 elif self_adjusted
> other_adjusted
:
787 return (-1)**self
._sign
788 else: # self_adjusted < other_adjusted
789 return -((-1)**self
._sign
)
791 # Note: The Decimal standard doesn't cover rich comparisons for
792 # Decimals. In particular, the specification is silent on the
793 # subject of what should happen for a comparison involving a NaN.
794 # We take the following approach:
796 # == comparisons involving a NaN always return False
797 # != comparisons involving a NaN always return True
798 # <, >, <= and >= comparisons involving a (quiet or signaling)
799 # NaN signal InvalidOperation, and return False if the
800 # InvalidOperation is not trapped.
802 # This behavior is designed to conform as closely as possible to
803 # that specified by IEEE 754.
805 def __eq__(self
, other
):
806 other
= _convert_other(other
)
807 if other
is NotImplemented:
809 if self
.is_nan() or other
.is_nan():
811 return self
._cmp
(other
) == 0
813 def __ne__(self
, other
):
814 other
= _convert_other(other
)
815 if other
is NotImplemented:
817 if self
.is_nan() or other
.is_nan():
819 return self
._cmp
(other
) != 0
821 def __lt__(self
, other
, context
=None):
822 other
= _convert_other(other
)
823 if other
is NotImplemented:
825 ans
= self
._compare
_check
_nans
(other
, context
)
828 return self
._cmp
(other
) < 0
830 def __le__(self
, other
, context
=None):
831 other
= _convert_other(other
)
832 if other
is NotImplemented:
834 ans
= self
._compare
_check
_nans
(other
, context
)
837 return self
._cmp
(other
) <= 0
839 def __gt__(self
, other
, context
=None):
840 other
= _convert_other(other
)
841 if other
is NotImplemented:
843 ans
= self
._compare
_check
_nans
(other
, context
)
846 return self
._cmp
(other
) > 0
848 def __ge__(self
, other
, context
=None):
849 other
= _convert_other(other
)
850 if other
is NotImplemented:
852 ans
= self
._compare
_check
_nans
(other
, context
)
855 return self
._cmp
(other
) >= 0
857 def compare(self
, other
, context
=None):
858 """Compares one to another.
864 Like __cmp__, but returns Decimal instances.
866 other
= _convert_other(other
, raiseit
=True)
868 # Compare(NaN, NaN) = NaN
869 if (self
._is
_special
or other
and other
._is
_special
):
870 ans
= self
._check
_nans
(other
, context
)
874 return Decimal(self
._cmp
(other
))
877 """x.__hash__() <==> hash(x)"""
878 # Decimal integers must hash the same as the ints
880 # The hash of a nonspecial noninteger Decimal must depend only
881 # on the value of that Decimal, and not on its representation.
882 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
885 raise TypeError('Cannot hash a NaN value.')
886 return hash(str(self
))
889 if self
._isinteger
():
890 op
= _WorkRep(self
.to_integral_value())
891 # to make computation feasible for Decimals with large
892 # exponent, we use the fact that hash(n) == hash(m) for
893 # any two nonzero integers n and m such that (i) n and m
894 # have the same sign, and (ii) n is congruent to m modulo
895 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
896 # hash((-1)**s*c*pow(10, e, 2**64-1).
897 return hash((-1)**op
.sign
*op
.int*pow(10, op
.exp
, 2**64-1))
898 # The value of a nonzero nonspecial Decimal instance is
899 # faithfully represented by the triple consisting of its sign,
900 # its adjusted exponent, and its coefficient with trailing
902 return hash((self
._sign
,
903 self
._exp
+len(self
._int
),
904 self
._int
.rstrip('0')))
907 """Represents the number as a triple tuple.
909 To show the internals exactly as they are.
911 return DecimalTuple(self
._sign
, tuple(map(int, self
._int
)), self
._exp
)
914 """Represents the number as an instance of Decimal."""
915 # Invariant: eval(repr(d)) == d
916 return "Decimal('%s')" % str(self
)
918 def __str__(self
, eng
=False, context
=None):
919 """Return string representation of the number in scientific notation.
921 Captures all of the information in the underlying representation.
924 sign
= ['', '-'][self
._sign
]
927 return sign
+ 'Infinity'
928 elif self
._exp
== 'n':
929 return sign
+ 'NaN' + self
._int
930 else: # self._exp == 'N'
931 return sign
+ 'sNaN' + self
._int
933 # number of digits of self._int to left of decimal point
934 leftdigits
= self
._exp
+ len(self
._int
)
936 # dotplace is number of digits of self._int to the left of the
937 # decimal point in the mantissa of the output string (that is,
938 # after adjusting the exponent)
939 if self
._exp
<= 0 and leftdigits
> -6:
940 # no exponent required
941 dotplace
= leftdigits
943 # usual scientific notation: 1 digit on left of the point
945 elif self
._int
== '0':
946 # engineering notation, zero
947 dotplace
= (leftdigits
+ 1) % 3 - 1
949 # engineering notation, nonzero
950 dotplace
= (leftdigits
- 1) % 3 + 1
954 fracpart
= '.' + '0'*(-dotplace
) + self
._int
955 elif dotplace
>= len(self
._int
):
956 intpart
= self
._int
+'0'*(dotplace
-len(self
._int
))
959 intpart
= self
._int
[:dotplace
]
960 fracpart
= '.' + self
._int
[dotplace
:]
961 if leftdigits
== dotplace
:
965 context
= getcontext()
966 exp
= ['e', 'E'][context
.capitals
] + "%+d" % (leftdigits
-dotplace
)
968 return sign
+ intpart
+ fracpart
+ exp
970 def to_eng_string(self
, context
=None):
971 """Convert to engineering-type string.
973 Engineering notation has an exponent which is a multiple of 3, so there
974 are up to 3 digits left of the decimal place.
976 Same rules for when in exponential and when as a value as in __str__.
978 return self
.__str
__(eng
=True, context
=context
)
980 def __neg__(self
, context
=None):
981 """Returns a copy with the sign switched.
983 Rounds, if it has reason.
986 ans
= self
._check
_nans
(context
=context
)
991 # -Decimal('0') is Decimal('0'), not Decimal('-0')
992 ans
= self
.copy_abs()
994 ans
= self
.copy_negate()
997 context
= getcontext()
998 return ans
._fix
(context
)
1000 def __pos__(self
, context
=None):
1001 """Returns a copy, unless it is a sNaN.
1003 Rounds the number (if more then precision digits)
1005 if self
._is
_special
:
1006 ans
= self
._check
_nans
(context
=context
)
1012 ans
= self
.copy_abs()
1017 context
= getcontext()
1018 return ans
._fix
(context
)
1020 def __abs__(self
, round=True, context
=None):
1021 """Returns the absolute value of self.
1023 If the keyword argument 'round' is false, do not round. The
1024 expression self.__abs__(round=False) is equivalent to
1028 return self
.copy_abs()
1030 if self
._is
_special
:
1031 ans
= self
._check
_nans
(context
=context
)
1036 ans
= self
.__neg
__(context
=context
)
1038 ans
= self
.__pos
__(context
=context
)
1042 def __add__(self
, other
, context
=None):
1043 """Returns self + other.
1045 -INF + INF (or the reverse) cause InvalidOperation errors.
1047 other
= _convert_other(other
)
1048 if other
is NotImplemented:
1052 context
= getcontext()
1054 if self
._is
_special
or other
._is
_special
:
1055 ans
= self
._check
_nans
(other
, context
)
1059 if self
._isinfinity
():
1060 # If both INF, same sign => same as both, opposite => error.
1061 if self
._sign
!= other
._sign
and other
._isinfinity
():
1062 return context
._raise
_error
(InvalidOperation
, '-INF + INF')
1063 return Decimal(self
)
1064 if other
._isinfinity
():
1065 return Decimal(other
) # Can't both be infinity here
1067 exp
= min(self
._exp
, other
._exp
)
1069 if context
.rounding
== ROUND_FLOOR
and self
._sign
!= other
._sign
:
1070 # If the answer is 0, the sign should be negative, in this case.
1073 if not self
and not other
:
1074 sign
= min(self
._sign
, other
._sign
)
1077 ans
= _dec_from_triple(sign
, '0', exp
)
1078 ans
= ans
._fix
(context
)
1081 exp
= max(exp
, other
._exp
- context
.prec
-1)
1082 ans
= other
._rescale
(exp
, context
.rounding
)
1083 ans
= ans
._fix
(context
)
1086 exp
= max(exp
, self
._exp
- context
.prec
-1)
1087 ans
= self
._rescale
(exp
, context
.rounding
)
1088 ans
= ans
._fix
(context
)
1091 op1
= _WorkRep(self
)
1092 op2
= _WorkRep(other
)
1093 op1
, op2
= _normalize(op1
, op2
, context
.prec
)
1096 if op1
.sign
!= op2
.sign
:
1097 # Equal and opposite
1098 if op1
.int == op2
.int:
1099 ans
= _dec_from_triple(negativezero
, '0', exp
)
1100 ans
= ans
._fix
(context
)
1102 if op1
.int < op2
.int:
1104 # OK, now abs(op1) > abs(op2)
1107 op1
.sign
, op2
.sign
= op2
.sign
, op1
.sign
1110 # So we know the sign, and op1 > 0.
1113 op1
.sign
, op2
.sign
= (0, 0)
1116 # Now, op1 > abs(op2) > 0
1119 result
.int = op1
.int + op2
.int
1121 result
.int = op1
.int - op2
.int
1123 result
.exp
= op1
.exp
1124 ans
= Decimal(result
)
1125 ans
= ans
._fix
(context
)
1130 def __sub__(self
, other
, context
=None):
1131 """Return self - other"""
1132 other
= _convert_other(other
)
1133 if other
is NotImplemented:
1136 if self
._is
_special
or other
._is
_special
:
1137 ans
= self
._check
_nans
(other
, context
=context
)
1141 # self - other is computed as self + other.copy_negate()
1142 return self
.__add
__(other
.copy_negate(), context
=context
)
1144 def __rsub__(self
, other
, context
=None):
1145 """Return other - self"""
1146 other
= _convert_other(other
)
1147 if other
is NotImplemented:
1150 return other
.__sub
__(self
, context
=context
)
1152 def __mul__(self
, other
, context
=None):
1153 """Return self * other.
1155 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1157 other
= _convert_other(other
)
1158 if other
is NotImplemented:
1162 context
= getcontext()
1164 resultsign
= self
._sign ^ other
._sign
1166 if self
._is
_special
or other
._is
_special
:
1167 ans
= self
._check
_nans
(other
, context
)
1171 if self
._isinfinity
():
1173 return context
._raise
_error
(InvalidOperation
, '(+-)INF * 0')
1174 return Infsign
[resultsign
]
1176 if other
._isinfinity
():
1178 return context
._raise
_error
(InvalidOperation
, '0 * (+-)INF')
1179 return Infsign
[resultsign
]
1181 resultexp
= self
._exp
+ other
._exp
1183 # Special case for multiplying by zero
1184 if not self
or not other
:
1185 ans
= _dec_from_triple(resultsign
, '0', resultexp
)
1186 # Fixing in case the exponent is out of bounds
1187 ans
= ans
._fix
(context
)
1190 # Special case for multiplying by power of 10
1191 if self
._int
== '1':
1192 ans
= _dec_from_triple(resultsign
, other
._int
, resultexp
)
1193 ans
= ans
._fix
(context
)
1195 if other
._int
== '1':
1196 ans
= _dec_from_triple(resultsign
, self
._int
, resultexp
)
1197 ans
= ans
._fix
(context
)
1200 op1
= _WorkRep(self
)
1201 op2
= _WorkRep(other
)
1203 ans
= _dec_from_triple(resultsign
, str(op1
.int * op2
.int), resultexp
)
1204 ans
= ans
._fix
(context
)
1209 def __truediv__(self
, other
, context
=None):
1210 """Return self / other."""
1211 other
= _convert_other(other
)
1212 if other
is NotImplemented:
1213 return NotImplemented
1216 context
= getcontext()
1218 sign
= self
._sign ^ other
._sign
1220 if self
._is
_special
or other
._is
_special
:
1221 ans
= self
._check
_nans
(other
, context
)
1225 if self
._isinfinity
() and other
._isinfinity
():
1226 return context
._raise
_error
(InvalidOperation
, '(+-)INF/(+-)INF')
1228 if self
._isinfinity
():
1229 return Infsign
[sign
]
1231 if other
._isinfinity
():
1232 context
._raise
_error
(Clamped
, 'Division by infinity')
1233 return _dec_from_triple(sign
, '0', context
.Etiny())
1235 # Special cases for zeroes
1238 return context
._raise
_error
(DivisionUndefined
, '0 / 0')
1239 return context
._raise
_error
(DivisionByZero
, 'x / 0', sign
)
1242 exp
= self
._exp
- other
._exp
1245 # OK, so neither = 0, INF or NaN
1246 shift
= len(other
._int
) - len(self
._int
) + context
.prec
+ 1
1247 exp
= self
._exp
- other
._exp
- shift
1248 op1
= _WorkRep(self
)
1249 op2
= _WorkRep(other
)
1251 coeff
, remainder
= divmod(op1
.int * 10**shift
, op2
.int)
1253 coeff
, remainder
= divmod(op1
.int, op2
.int * 10**-shift
)
1255 # result is not exact; adjust to ensure correct rounding
1259 # result is exact; get as close to ideal exponent as possible
1260 ideal_exp
= self
._exp
- other
._exp
1261 while exp
< ideal_exp
and coeff
% 10 == 0:
1265 ans
= _dec_from_triple(sign
, str(coeff
), exp
)
1266 return ans
._fix
(context
)
1268 def _divide(self
, other
, context
):
1269 """Return (self // other, self % other), to context.prec precision.
1271 Assumes that neither self nor other is a NaN, that self is not
1272 infinite and that other is nonzero.
1274 sign
= self
._sign ^ other
._sign
1275 if other
._isinfinity
():
1276 ideal_exp
= self
._exp
1278 ideal_exp
= min(self
._exp
, other
._exp
)
1280 expdiff
= self
.adjusted() - other
.adjusted()
1281 if not self
or other
._isinfinity
() or expdiff
<= -2:
1282 return (_dec_from_triple(sign
, '0', 0),
1283 self
._rescale
(ideal_exp
, context
.rounding
))
1284 if expdiff
<= context
.prec
:
1285 op1
= _WorkRep(self
)
1286 op2
= _WorkRep(other
)
1287 if op1
.exp
>= op2
.exp
:
1288 op1
.int *= 10**(op1
.exp
- op2
.exp
)
1290 op2
.int *= 10**(op2
.exp
- op1
.exp
)
1291 q
, r
= divmod(op1
.int, op2
.int)
1292 if q
< 10**context
.prec
:
1293 return (_dec_from_triple(sign
, str(q
), 0),
1294 _dec_from_triple(self
._sign
, str(r
), ideal_exp
))
1296 # Here the quotient is too large to be representable
1297 ans
= context
._raise
_error
(DivisionImpossible
,
1298 'quotient too large in //, % or divmod')
1301 def __rtruediv__(self
, other
, context
=None):
1302 """Swaps self/other and returns __truediv__."""
1303 other
= _convert_other(other
)
1304 if other
is NotImplemented:
1306 return other
.__truediv
__(self
, context
=context
)
1308 __div__
= __truediv__
1309 __rdiv__
= __rtruediv__
1311 def __divmod__(self
, other
, context
=None):
1313 Return (self // other, self % other)
1315 other
= _convert_other(other
)
1316 if other
is NotImplemented:
1320 context
= getcontext()
1322 ans
= self
._check
_nans
(other
, context
)
1326 sign
= self
._sign ^ other
._sign
1327 if self
._isinfinity
():
1328 if other
._isinfinity
():
1329 ans
= context
._raise
_error
(InvalidOperation
, 'divmod(INF, INF)')
1332 return (Infsign
[sign
],
1333 context
._raise
_error
(InvalidOperation
, 'INF % x'))
1337 ans
= context
._raise
_error
(DivisionUndefined
, 'divmod(0, 0)')
1340 return (context
._raise
_error
(DivisionByZero
, 'x // 0', sign
),
1341 context
._raise
_error
(InvalidOperation
, 'x % 0'))
1343 quotient
, remainder
= self
._divide
(other
, context
)
1344 remainder
= remainder
._fix
(context
)
1345 return quotient
, remainder
1347 def __rdivmod__(self
, other
, context
=None):
1348 """Swaps self/other and returns __divmod__."""
1349 other
= _convert_other(other
)
1350 if other
is NotImplemented:
1352 return other
.__divmod
__(self
, context
=context
)
1354 def __mod__(self
, other
, context
=None):
1358 other
= _convert_other(other
)
1359 if other
is NotImplemented:
1363 context
= getcontext()
1365 ans
= self
._check
_nans
(other
, context
)
1369 if self
._isinfinity
():
1370 return context
._raise
_error
(InvalidOperation
, 'INF % x')
1373 return context
._raise
_error
(InvalidOperation
, 'x % 0')
1375 return context
._raise
_error
(DivisionUndefined
, '0 % 0')
1377 remainder
= self
._divide
(other
, context
)[1]
1378 remainder
= remainder
._fix
(context
)
1381 def __rmod__(self
, other
, context
=None):
1382 """Swaps self/other and returns __mod__."""
1383 other
= _convert_other(other
)
1384 if other
is NotImplemented:
1386 return other
.__mod
__(self
, context
=context
)
1388 def remainder_near(self
, other
, context
=None):
1390 Remainder nearest to 0- abs(remainder-near) <= other/2
1393 context
= getcontext()
1395 other
= _convert_other(other
, raiseit
=True)
1397 ans
= self
._check
_nans
(other
, context
)
1401 # self == +/-infinity -> InvalidOperation
1402 if self
._isinfinity
():
1403 return context
._raise
_error
(InvalidOperation
,
1404 'remainder_near(infinity, x)')
1406 # other == 0 -> either InvalidOperation or DivisionUndefined
1409 return context
._raise
_error
(InvalidOperation
,
1410 'remainder_near(x, 0)')
1412 return context
._raise
_error
(DivisionUndefined
,
1413 'remainder_near(0, 0)')
1415 # other = +/-infinity -> remainder = self
1416 if other
._isinfinity
():
1418 return ans
._fix
(context
)
1420 # self = 0 -> remainder = self, with ideal exponent
1421 ideal_exponent
= min(self
._exp
, other
._exp
)
1423 ans
= _dec_from_triple(self
._sign
, '0', ideal_exponent
)
1424 return ans
._fix
(context
)
1426 # catch most cases of large or small quotient
1427 expdiff
= self
.adjusted() - other
.adjusted()
1428 if expdiff
>= context
.prec
+ 1:
1429 # expdiff >= prec+1 => abs(self/other) > 10**prec
1430 return context
._raise
_error
(DivisionImpossible
)
1432 # expdiff <= -2 => abs(self/other) < 0.1
1433 ans
= self
._rescale
(ideal_exponent
, context
.rounding
)
1434 return ans
._fix
(context
)
1436 # adjust both arguments to have the same exponent, then divide
1437 op1
= _WorkRep(self
)
1438 op2
= _WorkRep(other
)
1439 if op1
.exp
>= op2
.exp
:
1440 op1
.int *= 10**(op1
.exp
- op2
.exp
)
1442 op2
.int *= 10**(op2
.exp
- op1
.exp
)
1443 q
, r
= divmod(op1
.int, op2
.int)
1444 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1445 # 10**ideal_exponent. Apply correction to ensure that
1446 # abs(remainder) <= abs(other)/2
1447 if 2*r
+ (q
&1) > op2
.int:
1451 if q
>= 10**context
.prec
:
1452 return context
._raise
_error
(DivisionImpossible
)
1454 # result has same sign as self unless r is negative
1460 ans
= _dec_from_triple(sign
, str(r
), ideal_exponent
)
1461 return ans
._fix
(context
)
1463 def __floordiv__(self
, other
, context
=None):
1465 other
= _convert_other(other
)
1466 if other
is NotImplemented:
1470 context
= getcontext()
1472 ans
= self
._check
_nans
(other
, context
)
1476 if self
._isinfinity
():
1477 if other
._isinfinity
():
1478 return context
._raise
_error
(InvalidOperation
, 'INF // INF')
1480 return Infsign
[self
._sign ^ other
._sign
]
1484 return context
._raise
_error
(DivisionByZero
, 'x // 0',
1485 self
._sign ^ other
._sign
)
1487 return context
._raise
_error
(DivisionUndefined
, '0 // 0')
1489 return self
._divide
(other
, context
)[0]
1491 def __rfloordiv__(self
, other
, context
=None):
1492 """Swaps self/other and returns __floordiv__."""
1493 other
= _convert_other(other
)
1494 if other
is NotImplemented:
1496 return other
.__floordiv
__(self
, context
=context
)
1498 def __float__(self
):
1499 """Float representation."""
1500 return float(str(self
))
1503 """Converts self to an int, truncating if necessary."""
1504 if self
._is
_special
:
1506 context
= getcontext()
1507 return context
._raise
_error
(InvalidContext
)
1508 elif self
._isinfinity
():
1509 raise OverflowError("Cannot convert infinity to int")
1510 s
= (-1)**self
._sign
1512 return s
*int(self
._int
)*10**self
._exp
1514 return s
*int(self
._int
[:self
._exp
] or '0')
1526 def conjugate(self
):
1529 def __complex__(self
):
1530 return complex(float(self
))
1533 """Converts to a long.
1535 Equivalent to long(int(self))
1537 return long(self
.__int
__())
1539 def _fix_nan(self
, context
):
1540 """Decapitate the payload of a NaN to fit the context"""
1543 # maximum length of payload is precision if _clamp=0,
1544 # precision-1 if _clamp=1.
1545 max_payload_len
= context
.prec
- context
._clamp
1546 if len(payload
) > max_payload_len
:
1547 payload
= payload
[len(payload
)-max_payload_len
:].lstrip('0')
1548 return _dec_from_triple(self
._sign
, payload
, self
._exp
, True)
1549 return Decimal(self
)
1551 def _fix(self
, context
):
1552 """Round if it is necessary to keep self within prec precision.
1554 Rounds and fixes the exponent. Does not raise on a sNaN.
1557 self - Decimal instance
1558 context - context used.
1561 if self
._is
_special
:
1563 # decapitate payload if necessary
1564 return self
._fix
_nan
(context
)
1566 # self is +/-Infinity; return unaltered
1567 return Decimal(self
)
1569 # if self is zero then exponent should be between Etiny and
1570 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1571 Etiny
= context
.Etiny()
1572 Etop
= context
.Etop()
1574 exp_max
= [context
.Emax
, Etop
][context
._clamp
]
1575 new_exp
= min(max(self
._exp
, Etiny
), exp_max
)
1576 if new_exp
!= self
._exp
:
1577 context
._raise
_error
(Clamped
)
1578 return _dec_from_triple(self
._sign
, '0', new_exp
)
1580 return Decimal(self
)
1582 # exp_min is the smallest allowable exponent of the result,
1583 # equal to max(self.adjusted()-context.prec+1, Etiny)
1584 exp_min
= len(self
._int
) + self
._exp
- context
.prec
1586 # overflow: exp_min > Etop iff self.adjusted() > Emax
1587 context
._raise
_error
(Inexact
)
1588 context
._raise
_error
(Rounded
)
1589 return context
._raise
_error
(Overflow
, 'above Emax', self
._sign
)
1590 self_is_subnormal
= exp_min
< Etiny
1591 if self_is_subnormal
:
1592 context
._raise
_error
(Subnormal
)
1595 # round if self has too many digits
1596 if self
._exp
< exp_min
:
1597 context
._raise
_error
(Rounded
)
1598 digits
= len(self
._int
) + self
._exp
- exp_min
1600 self
= _dec_from_triple(self
._sign
, '1', exp_min
-1)
1602 this_function
= getattr(self
, self
._pick
_rounding
_function
[context
.rounding
])
1603 changed
= this_function(digits
)
1604 coeff
= self
._int
[:digits
] or '0'
1606 coeff
= str(int(coeff
)+1)
1607 ans
= _dec_from_triple(self
._sign
, coeff
, exp_min
)
1610 context
._raise
_error
(Inexact
)
1611 if self_is_subnormal
:
1612 context
._raise
_error
(Underflow
)
1614 # raise Clamped on underflow to 0
1615 context
._raise
_error
(Clamped
)
1616 elif len(ans
._int
) == context
.prec
+1:
1617 # we get here only if rescaling rounds the
1618 # cofficient up to exactly 10**context.prec
1620 ans
= _dec_from_triple(ans
._sign
,
1621 ans
._int
[:-1], ans
._exp
+1)
1623 # Inexact and Rounded have already been raised
1624 ans
= context
._raise
_error
(Overflow
, 'above Emax',
1628 # fold down if _clamp == 1 and self has too few digits
1629 if context
._clamp
== 1 and self
._exp
> Etop
:
1630 context
._raise
_error
(Clamped
)
1631 self_padded
= self
._int
+ '0'*(self
._exp
- Etop
)
1632 return _dec_from_triple(self
._sign
, self_padded
, Etop
)
1634 # here self was representable to begin with; return unchanged
1635 return Decimal(self
)
1637 _pick_rounding_function
= {}
1639 # for each of the rounding functions below:
1640 # self is a finite, nonzero Decimal
1641 # prec is an integer satisfying 0 <= prec < len(self._int)
1643 # each function returns either -1, 0, or 1, as follows:
1644 # 1 indicates that self should be rounded up (away from zero)
1645 # 0 indicates that self should be truncated, and that all the
1646 # digits to be truncated are zeros (so the value is unchanged)
1647 # -1 indicates that there are nonzero digits to be truncated
1649 def _round_down(self
, prec
):
1650 """Also known as round-towards-0, truncate."""
1651 if _all_zeros(self
._int
, prec
):
1656 def _round_up(self
, prec
):
1657 """Rounds away from 0."""
1658 return -self
._round
_down
(prec
)
1660 def _round_half_up(self
, prec
):
1661 """Rounds 5 up (away from 0)"""
1662 if self
._int
[prec
] in '56789':
1664 elif _all_zeros(self
._int
, prec
):
1669 def _round_half_down(self
, prec
):
1671 if _exact_half(self
._int
, prec
):
1674 return self
._round
_half
_up
(prec
)
1676 def _round_half_even(self
, prec
):
1677 """Round 5 to even, rest to nearest."""
1678 if _exact_half(self
._int
, prec
) and \
1679 (prec
== 0 or self
._int
[prec
-1] in '02468'):
1682 return self
._round
_half
_up
(prec
)
1684 def _round_ceiling(self
, prec
):
1685 """Rounds up (not away from 0 if negative.)"""
1687 return self
._round
_down
(prec
)
1689 return -self
._round
_down
(prec
)
1691 def _round_floor(self
, prec
):
1692 """Rounds down (not towards 0 if negative)"""
1694 return self
._round
_down
(prec
)
1696 return -self
._round
_down
(prec
)
1698 def _round_05up(self
, prec
):
1699 """Round down unless digit prec-1 is 0 or 5."""
1700 if prec
and self
._int
[prec
-1] not in '05':
1701 return self
._round
_down
(prec
)
1703 return -self
._round
_down
(prec
)
1705 def fma(self
, other
, third
, context
=None):
1706 """Fused multiply-add.
1708 Returns self*other+third with no rounding of the intermediate
1711 self and other are multiplied together, with no rounding of
1712 the result. The third operand is then added to the result,
1713 and a single final rounding is performed.
1716 other
= _convert_other(other
, raiseit
=True)
1718 # compute product; raise InvalidOperation if either operand is
1719 # a signaling NaN or if the product is zero times infinity.
1720 if self
._is
_special
or other
._is
_special
:
1722 context
= getcontext()
1723 if self
._exp
== 'N':
1724 return context
._raise
_error
(InvalidOperation
, 'sNaN', self
)
1725 if other
._exp
== 'N':
1726 return context
._raise
_error
(InvalidOperation
, 'sNaN', other
)
1727 if self
._exp
== 'n':
1729 elif other
._exp
== 'n':
1731 elif self
._exp
== 'F':
1733 return context
._raise
_error
(InvalidOperation
,
1735 product
= Infsign
[self
._sign ^ other
._sign
]
1736 elif other
._exp
== 'F':
1738 return context
._raise
_error
(InvalidOperation
,
1740 product
= Infsign
[self
._sign ^ other
._sign
]
1742 product
= _dec_from_triple(self
._sign ^ other
._sign
,
1743 str(int(self
._int
) * int(other
._int
)),
1744 self
._exp
+ other
._exp
)
1746 third
= _convert_other(third
, raiseit
=True)
1747 return product
.__add
__(third
, context
)
1749 def _power_modulo(self
, other
, modulo
, context
=None):
1750 """Three argument version of __pow__"""
1752 # if can't convert other and modulo to Decimal, raise
1753 # TypeError; there's no point returning NotImplemented (no
1754 # equivalent of __rpow__ for three argument pow)
1755 other
= _convert_other(other
, raiseit
=True)
1756 modulo
= _convert_other(modulo
, raiseit
=True)
1759 context
= getcontext()
1761 # deal with NaNs: if there are any sNaNs then first one wins,
1762 # (i.e. behaviour for NaNs is identical to that of fma)
1763 self_is_nan
= self
._isnan
()
1764 other_is_nan
= other
._isnan
()
1765 modulo_is_nan
= modulo
._isnan
()
1766 if self_is_nan
or other_is_nan
or modulo_is_nan
:
1767 if self_is_nan
== 2:
1768 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1770 if other_is_nan
== 2:
1771 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1773 if modulo_is_nan
== 2:
1774 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1777 return self
._fix
_nan
(context
)
1779 return other
._fix
_nan
(context
)
1780 return modulo
._fix
_nan
(context
)
1782 # check inputs: we apply same restrictions as Python's pow()
1783 if not (self
._isinteger
() and
1784 other
._isinteger
() and
1785 modulo
._isinteger
()):
1786 return context
._raise
_error
(InvalidOperation
,
1787 'pow() 3rd argument not allowed '
1788 'unless all arguments are integers')
1790 return context
._raise
_error
(InvalidOperation
,
1791 'pow() 2nd argument cannot be '
1792 'negative when 3rd argument specified')
1794 return context
._raise
_error
(InvalidOperation
,
1795 'pow() 3rd argument cannot be 0')
1797 # additional restriction for decimal: the modulus must be less
1798 # than 10**prec in absolute value
1799 if modulo
.adjusted() >= context
.prec
:
1800 return context
._raise
_error
(InvalidOperation
,
1801 'insufficient precision: pow() 3rd '
1802 'argument must not have more than '
1805 # define 0**0 == NaN, for consistency with two-argument pow
1806 # (even though it hurts!)
1807 if not other
and not self
:
1808 return context
._raise
_error
(InvalidOperation
,
1809 'at least one of pow() 1st argument '
1810 'and 2nd argument must be nonzero ;'
1811 '0**0 is not defined')
1813 # compute sign of result
1819 # convert modulo to a Python integer, and self and other to
1820 # Decimal integers (i.e. force their exponents to be >= 0)
1821 modulo
= abs(int(modulo
))
1822 base
= _WorkRep(self
.to_integral_value())
1823 exponent
= _WorkRep(other
.to_integral_value())
1825 # compute result using integer pow()
1826 base
= (base
.int % modulo
* pow(10, base
.exp
, modulo
)) % modulo
1827 for i
in xrange(exponent
.exp
):
1828 base
= pow(base
, 10, modulo
)
1829 base
= pow(base
, exponent
.int, modulo
)
1831 return _dec_from_triple(sign
, str(base
), 0)
1833 def _power_exact(self
, other
, p
):
1834 """Attempt to compute self**other exactly.
1836 Given Decimals self and other and an integer p, attempt to
1837 compute an exact result for the power self**other, with p
1838 digits of precision. Return None if self**other is not
1839 exactly representable in p digits.
1841 Assumes that elimination of special cases has already been
1842 performed: self and other must both be nonspecial; self must
1843 be positive and not numerically equal to 1; other must be
1844 nonzero. For efficiency, other._exp should not be too large,
1845 so that 10**abs(other._exp) is a feasible calculation."""
1847 # In the comments below, we write x for the value of self and
1848 # y for the value of other. Write x = xc*10**xe and y =
1851 # The main purpose of this method is to identify the *failure*
1852 # of x**y to be exactly representable with as little effort as
1853 # possible. So we look for cheap and easy tests that
1854 # eliminate the possibility of x**y being exact. Only if all
1855 # these tests are passed do we go on to actually compute x**y.
1857 # Here's the main idea. First normalize both x and y. We
1858 # express y as a rational m/n, with m and n relatively prime
1859 # and n>0. Then for x**y to be exactly representable (at
1860 # *any* precision), xc must be the nth power of a positive
1861 # integer and xe must be divisible by n. If m is negative
1862 # then additionally xc must be a power of either 2 or 5, hence
1863 # a power of 2**n or 5**n.
1865 # There's a limit to how small |y| can be: if y=m/n as above
1868 # (1) if xc != 1 then for the result to be representable we
1869 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1870 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1871 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1874 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1875 # |y| < 1/|xe| then the result is not representable.
1877 # Note that since x is not equal to 1, at least one of (1) and
1878 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1879 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1881 # There's also a limit to how large y can be, at least if it's
1882 # positive: the normalized result will have coefficient xc**y,
1883 # so if it's representable then xc**y < 10**p, and y <
1884 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1885 # not exactly representable.
1887 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1888 # so |y| < 1/xe and the result is not representable.
1889 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1893 xc
, xe
= x
.int, x
.exp
1899 yc
, ye
= y
.int, y
.exp
1904 # case where xc == 1: result is 10**(xe*y), with xe*y
1905 # required to be an integer
1908 exponent
= xe
*yc
*10**ye
1910 exponent
, remainder
= divmod(xe
*yc
, 10**-ye
)
1914 exponent
= -exponent
1915 # if other is a nonnegative integer, use ideal exponent
1916 if other
._isinteger
() and other
._sign
== 0:
1917 ideal_exponent
= self
._exp
*int(other
)
1918 zeros
= min(exponent
-ideal_exponent
, p
-1)
1921 return _dec_from_triple(0, '1' + '0'*zeros
, exponent
-zeros
)
1923 # case where y is negative: xc must be either a power
1924 # of 2 or a power of 5.
1926 last_digit
= xc
% 10
1927 if last_digit
in (2,4,6,8):
1928 # quick test for power of 2
1931 # now xc is a power of 2; e is its exponent
1933 # find e*y and xe*y; both must be integers
1935 y_as_int
= yc
*10**ye
1940 e
, remainder
= divmod(e
*yc
, ten_pow
)
1943 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1947 if e
*65 >= p
*93: # 93/65 > log(10)/log(5)
1951 elif last_digit
== 5:
1952 # e >= log_5(xc) if xc is a power of 5; we have
1953 # equality all the way up to xc=5**2658
1954 e
= _nbits(xc
)*28//65
1955 xc
, remainder
= divmod(5**e
, xc
)
1962 y_as_integer
= yc
*10**ye
1964 xe
= xe
*y_as_integer
1967 e
, remainder
= divmod(e
*yc
, ten_pow
)
1970 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1973 if e
*3 >= p
*10: # 10/3 > log(10)/log(2)
1982 return _dec_from_triple(0, str(xc
), xe
)
1984 # now y is positive; find m and n such that y = m/n
1988 if xe
!= 0 and len(str(abs(yc
*xe
))) <= -ye
:
1990 xc_bits
= _nbits(xc
)
1991 if xc
!= 1 and len(str(abs(yc
)*xc_bits
)) <= -ye
:
1993 m
, n
= yc
, 10**(-ye
)
1994 while m
% 2 == n
% 2 == 0:
1997 while m
% 5 == n
% 5 == 0:
2001 # compute nth root of xc*10**xe
2003 # if 1 < xc < 2**n then xc isn't an nth power
2004 if xc
!= 1 and xc_bits
<= n
:
2007 xe
, rem
= divmod(xe
, n
)
2011 # compute nth root of xc using Newton's method
2012 a
= 1L << -(-_nbits(xc
)//n
) # initial estimate
2014 q
, r
= divmod(xc
, a
**(n
-1))
2018 a
= (a
*(n
-1) + q
)//n
2019 if not (a
== q
and r
== 0):
2023 # now xc*10**xe is the nth root of the original xc*10**xe
2024 # compute mth power of xc*10**xe
2026 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2027 # 10**p and the result is not representable.
2028 if xc
> 1 and m
> p
*100//_log10_lb(xc
):
2035 # by this point the result *is* exactly representable
2036 # adjust the exponent to get as close as possible to the ideal
2037 # exponent, if necessary
2039 if other
._isinteger
() and other
._sign
== 0:
2040 ideal_exponent
= self
._exp
*int(other
)
2041 zeros
= min(xe
-ideal_exponent
, p
-len(str_xc
))
2044 return _dec_from_triple(0, str_xc
+'0'*zeros
, xe
-zeros
)
2046 def __pow__(self
, other
, modulo
=None, context
=None):
2047 """Return self ** other [ % modulo].
2049 With two arguments, compute self**other.
2051 With three arguments, compute (self**other) % modulo. For the
2052 three argument form, the following restrictions on the
2055 - all three arguments must be integral
2056 - other must be nonnegative
2057 - either self or other (or both) must be nonzero
2058 - modulo must be nonzero and must have at most p digits,
2059 where p is the context precision.
2061 If any of these restrictions is violated the InvalidOperation
2064 The result of pow(self, other, modulo) is identical to the
2065 result that would be obtained by computing (self**other) %
2066 modulo with unbounded precision, but is computed more
2067 efficiently. It is always exact.
2070 if modulo
is not None:
2071 return self
._power
_modulo
(other
, modulo
, context
)
2073 other
= _convert_other(other
)
2074 if other
is NotImplemented:
2078 context
= getcontext()
2080 # either argument is a NaN => result is NaN
2081 ans
= self
._check
_nans
(other
, context
)
2085 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2088 return context
._raise
_error
(InvalidOperation
, '0 ** 0')
2092 # result has sign 1 iff self._sign is 1 and other is an odd integer
2095 if other
._isinteger
():
2096 if not other
._iseven
():
2099 # -ve**noninteger = NaN
2100 # (-0)**noninteger = 0**noninteger
2102 return context
._raise
_error
(InvalidOperation
,
2103 'x ** y with x negative and y not an integer')
2104 # negate self, without doing any unwanted rounding
2105 self
= self
.copy_negate()
2107 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2109 if other
._sign
== 0:
2110 return _dec_from_triple(result_sign
, '0', 0)
2112 return Infsign
[result_sign
]
2114 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2115 if self
._isinfinity
():
2116 if other
._sign
== 0:
2117 return Infsign
[result_sign
]
2119 return _dec_from_triple(result_sign
, '0', 0)
2121 # 1**other = 1, but the choice of exponent and the flags
2122 # depend on the exponent of self, and on whether other is a
2123 # positive integer, a negative integer, or neither
2125 if other
._isinteger
():
2126 # exp = max(self._exp*max(int(other), 0),
2127 # 1-context.prec) but evaluating int(other) directly
2128 # is dangerous until we know other is small (other
2129 # could be 1e999999999)
2130 if other
._sign
== 1:
2132 elif other
> context
.prec
:
2133 multiplier
= context
.prec
2135 multiplier
= int(other
)
2137 exp
= self
._exp
* multiplier
2138 if exp
< 1-context
.prec
:
2139 exp
= 1-context
.prec
2140 context
._raise
_error
(Rounded
)
2142 context
._raise
_error
(Inexact
)
2143 context
._raise
_error
(Rounded
)
2144 exp
= 1-context
.prec
2146 return _dec_from_triple(result_sign
, '1'+'0'*-exp
, exp
)
2148 # compute adjusted exponent of self
2149 self_adj
= self
.adjusted()
2151 # self ** infinity is infinity if self > 1, 0 if self < 1
2152 # self ** -infinity is infinity if self < 1, 0 if self > 1
2153 if other
._isinfinity
():
2154 if (other
._sign
== 0) == (self_adj
< 0):
2155 return _dec_from_triple(result_sign
, '0', 0)
2157 return Infsign
[result_sign
]
2159 # from here on, the result always goes through the call
2160 # to _fix at the end of this function.
2163 # crude test to catch cases of extreme overflow/underflow. If
2164 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2165 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2166 # self**other >= 10**(Emax+1), so overflow occurs. The test
2167 # for underflow is similar.
2168 bound
= self
._log
10_exp
_bound
() + other
.adjusted()
2169 if (self_adj
>= 0) == (other
._sign
== 0):
2170 # self > 1 and other +ve, or self < 1 and other -ve
2171 # possibility of overflow
2172 if bound
>= len(str(context
.Emax
)):
2173 ans
= _dec_from_triple(result_sign
, '1', context
.Emax
+1)
2175 # self > 1 and other -ve, or self < 1 and other +ve
2176 # possibility of underflow to 0
2177 Etiny
= context
.Etiny()
2178 if bound
>= len(str(-Etiny
)):
2179 ans
= _dec_from_triple(result_sign
, '1', Etiny
-1)
2181 # try for an exact result with precision +1
2183 ans
= self
._power
_exact
(other
, context
.prec
+ 1)
2184 if ans
is not None and result_sign
== 1:
2185 ans
= _dec_from_triple(1, ans
._int
, ans
._exp
)
2187 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2191 xc
, xe
= x
.int, x
.exp
2193 yc
, ye
= y
.int, y
.exp
2197 # compute correctly rounded result: start with precision +3,
2198 # then increase precision until result is unambiguously roundable
2201 coeff
, exp
= _dpower(xc
, xe
, yc
, ye
, p
+extra
)
2202 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
2206 ans
= _dec_from_triple(result_sign
, str(coeff
), exp
)
2208 # the specification says that for non-integer other we need to
2209 # raise Inexact, even when the result is actually exact. In
2210 # the same way, we need to raise Underflow here if the result
2211 # is subnormal. (The call to _fix will take care of raising
2212 # Rounded and Subnormal, as usual.)
2213 if not other
._isinteger
():
2214 context
._raise
_error
(Inexact
)
2215 # pad with zeros up to length context.prec+1 if necessary
2216 if len(ans
._int
) <= context
.prec
:
2217 expdiff
= context
.prec
+1 - len(ans
._int
)
2218 ans
= _dec_from_triple(ans
._sign
, ans
._int
+'0'*expdiff
,
2220 if ans
.adjusted() < context
.Emin
:
2221 context
._raise
_error
(Underflow
)
2223 # unlike exp, ln and log10, the power function respects the
2224 # rounding mode; no need to use ROUND_HALF_EVEN here
2225 ans
= ans
._fix
(context
)
2228 def __rpow__(self
, other
, context
=None):
2229 """Swaps self/other and returns __pow__."""
2230 other
= _convert_other(other
)
2231 if other
is NotImplemented:
2233 return other
.__pow
__(self
, context
=context
)
2235 def normalize(self
, context
=None):
2236 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2239 context
= getcontext()
2241 if self
._is
_special
:
2242 ans
= self
._check
_nans
(context
=context
)
2246 dup
= self
._fix
(context
)
2247 if dup
._isinfinity
():
2251 return _dec_from_triple(dup
._sign
, '0', 0)
2252 exp_max
= [context
.Emax
, context
.Etop()][context
._clamp
]
2255 while dup
._int
[end
-1] == '0' and exp
< exp_max
:
2258 return _dec_from_triple(dup
._sign
, dup
._int
[:end
], exp
)
2260 def quantize(self
, exp
, rounding
=None, context
=None, watchexp
=True):
2261 """Quantize self so its exponent is the same as that of exp.
2263 Similar to self._rescale(exp._exp) but with error checking.
2265 exp
= _convert_other(exp
, raiseit
=True)
2268 context
= getcontext()
2269 if rounding
is None:
2270 rounding
= context
.rounding
2272 if self
._is
_special
or exp
._is
_special
:
2273 ans
= self
._check
_nans
(exp
, context
)
2277 if exp
._isinfinity
() or self
._isinfinity
():
2278 if exp
._isinfinity
() and self
._isinfinity
():
2279 return Decimal(self
) # if both are inf, it is OK
2280 return context
._raise
_error
(InvalidOperation
,
2281 'quantize with one INF')
2283 # if we're not watching exponents, do a simple rescale
2285 ans
= self
._rescale
(exp
._exp
, rounding
)
2286 # raise Inexact and Rounded where appropriate
2287 if ans
._exp
> self
._exp
:
2288 context
._raise
_error
(Rounded
)
2290 context
._raise
_error
(Inexact
)
2293 # exp._exp should be between Etiny and Emax
2294 if not (context
.Etiny() <= exp
._exp
<= context
.Emax
):
2295 return context
._raise
_error
(InvalidOperation
,
2296 'target exponent out of bounds in quantize')
2299 ans
= _dec_from_triple(self
._sign
, '0', exp
._exp
)
2300 return ans
._fix
(context
)
2302 self_adjusted
= self
.adjusted()
2303 if self_adjusted
> context
.Emax
:
2304 return context
._raise
_error
(InvalidOperation
,
2305 'exponent of quantize result too large for current context')
2306 if self_adjusted
- exp
._exp
+ 1 > context
.prec
:
2307 return context
._raise
_error
(InvalidOperation
,
2308 'quantize result has too many digits for current context')
2310 ans
= self
._rescale
(exp
._exp
, rounding
)
2311 if ans
.adjusted() > context
.Emax
:
2312 return context
._raise
_error
(InvalidOperation
,
2313 'exponent of quantize result too large for current context')
2314 if len(ans
._int
) > context
.prec
:
2315 return context
._raise
_error
(InvalidOperation
,
2316 'quantize result has too many digits for current context')
2318 # raise appropriate flags
2319 if ans
._exp
> self
._exp
:
2320 context
._raise
_error
(Rounded
)
2322 context
._raise
_error
(Inexact
)
2323 if ans
and ans
.adjusted() < context
.Emin
:
2324 context
._raise
_error
(Subnormal
)
2326 # call to fix takes care of any necessary folddown
2327 ans
= ans
._fix
(context
)
2330 def same_quantum(self
, other
):
2331 """Return True if self and other have the same exponent; otherwise
2334 If either operand is a special value, the following rules are used:
2335 * return True if both operands are infinities
2336 * return True if both operands are NaNs
2337 * otherwise, return False.
2339 other
= _convert_other(other
, raiseit
=True)
2340 if self
._is
_special
or other
._is
_special
:
2341 return (self
.is_nan() and other
.is_nan() or
2342 self
.is_infinite() and other
.is_infinite())
2343 return self
._exp
== other
._exp
2345 def _rescale(self
, exp
, rounding
):
2346 """Rescale self so that the exponent is exp, either by padding with zeros
2347 or by truncating digits, using the given rounding mode.
2349 Specials are returned without change. This operation is
2350 quiet: it raises no flags, and uses no information from the
2353 exp = exp to scale to (an integer)
2354 rounding = rounding mode
2356 if self
._is
_special
:
2357 return Decimal(self
)
2359 return _dec_from_triple(self
._sign
, '0', exp
)
2361 if self
._exp
>= exp
:
2362 # pad answer with zeros if necessary
2363 return _dec_from_triple(self
._sign
,
2364 self
._int
+ '0'*(self
._exp
- exp
), exp
)
2366 # too many digits; round and lose data. If self.adjusted() <
2367 # exp-1, replace self by 10**(exp-1) before rounding
2368 digits
= len(self
._int
) + self
._exp
- exp
2370 self
= _dec_from_triple(self
._sign
, '1', exp
-1)
2372 this_function
= getattr(self
, self
._pick
_rounding
_function
[rounding
])
2373 changed
= this_function(digits
)
2374 coeff
= self
._int
[:digits
] or '0'
2376 coeff
= str(int(coeff
)+1)
2377 return _dec_from_triple(self
._sign
, coeff
, exp
)
2379 def _round(self
, places
, rounding
):
2380 """Round a nonzero, nonspecial Decimal to a fixed number of
2381 significant figures, using the given rounding mode.
2383 Infinities, NaNs and zeros are returned unaltered.
2385 This operation is quiet: it raises no flags, and uses no
2386 information from the context.
2390 raise ValueError("argument should be at least 1 in _round")
2391 if self
._is
_special
or not self
:
2392 return Decimal(self
)
2393 ans
= self
._rescale
(self
.adjusted()+1-places
, rounding
)
2394 # it can happen that the rescale alters the adjusted exponent;
2395 # for example when rounding 99.97 to 3 significant figures.
2396 # When this happens we end up with an extra 0 at the end of
2397 # the number; a second rescale fixes this.
2398 if ans
.adjusted() != self
.adjusted():
2399 ans
= ans
._rescale
(ans
.adjusted()+1-places
, rounding
)
2402 def to_integral_exact(self
, rounding
=None, context
=None):
2403 """Rounds to a nearby integer.
2405 If no rounding mode is specified, take the rounding mode from
2406 the context. This method raises the Rounded and Inexact flags
2409 See also: to_integral_value, which does exactly the same as
2410 this method except that it doesn't raise Inexact or Rounded.
2412 if self
._is
_special
:
2413 ans
= self
._check
_nans
(context
=context
)
2416 return Decimal(self
)
2418 return Decimal(self
)
2420 return _dec_from_triple(self
._sign
, '0', 0)
2422 context
= getcontext()
2423 if rounding
is None:
2424 rounding
= context
.rounding
2425 context
._raise
_error
(Rounded
)
2426 ans
= self
._rescale
(0, rounding
)
2428 context
._raise
_error
(Inexact
)
2431 def to_integral_value(self
, rounding
=None, context
=None):
2432 """Rounds to the nearest integer, without raising inexact, rounded."""
2434 context
= getcontext()
2435 if rounding
is None:
2436 rounding
= context
.rounding
2437 if self
._is
_special
:
2438 ans
= self
._check
_nans
(context
=context
)
2441 return Decimal(self
)
2443 return Decimal(self
)
2445 return self
._rescale
(0, rounding
)
2447 # the method name changed, but we provide also the old one, for compatibility
2448 to_integral
= to_integral_value
2450 def sqrt(self
, context
=None):
2451 """Return the square root of self."""
2453 context
= getcontext()
2455 if self
._is
_special
:
2456 ans
= self
._check
_nans
(context
=context
)
2460 if self
._isinfinity
() and self
._sign
== 0:
2461 return Decimal(self
)
2464 # exponent = self._exp // 2. sqrt(-0) = -0
2465 ans
= _dec_from_triple(self
._sign
, '0', self
._exp
// 2)
2466 return ans
._fix
(context
)
2469 return context
._raise
_error
(InvalidOperation
, 'sqrt(-x), x > 0')
2471 # At this point self represents a positive number. Let p be
2472 # the desired precision and express self in the form c*100**e
2473 # with c a positive real number and e an integer, c and e
2474 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2475 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2476 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2477 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2478 # the closest integer to sqrt(c) with the even integer chosen
2479 # in the case of a tie.
2481 # To ensure correct rounding in all cases, we use the
2482 # following trick: we compute the square root to an extra
2483 # place (precision p+1 instead of precision p), rounding down.
2484 # Then, if the result is inexact and its last digit is 0 or 5,
2485 # we increase the last digit to 1 or 6 respectively; if it's
2486 # exact we leave the last digit alone. Now the final round to
2487 # p places (or fewer in the case of underflow) will round
2488 # correctly and raise the appropriate flags.
2490 # use an extra digit of precision
2491 prec
= context
.prec
+1
2493 # write argument in the form c*100**e where e = self._exp//2
2494 # is the 'ideal' exponent, to be used if the square root is
2495 # exactly representable. l is the number of 'digits' of c in
2496 # base 100, so that 100**(l-1) <= c < 100**l.
2501 l
= (len(self
._int
) >> 1) + 1
2504 l
= len(self
._int
)+1 >> 1
2506 # rescale so that c has exactly prec base 100 'digits'
2512 c
, remainder
= divmod(c
, 100**-shift
)
2513 exact
= not remainder
2516 # find n = floor(sqrt(c)) using Newton's method
2524 exact
= exact
and n
*n
== c
2527 # result is exact; rescale to use ideal exponent e
2529 # assert n % 10**shift == 0
2535 # result is not exact; fix last digit as described above
2539 ans
= _dec_from_triple(0, str(n
), e
)
2541 # round, and fit to current context
2542 context
= context
._shallow
_copy
()
2543 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2544 ans
= ans
._fix
(context
)
2545 context
.rounding
= rounding
2549 def max(self
, other
, context
=None):
2550 """Returns the larger value.
2552 Like max(self, other) except if one is not a number, returns
2553 NaN (and signals if one is sNaN). Also rounds.
2555 other
= _convert_other(other
, raiseit
=True)
2558 context
= getcontext()
2560 if self
._is
_special
or other
._is
_special
:
2561 # If one operand is a quiet NaN and the other is number, then the
2562 # number is always returned
2566 if on
== 1 and sn
== 0:
2567 return self
._fix
(context
)
2568 if sn
== 1 and on
== 0:
2569 return other
._fix
(context
)
2570 return self
._check
_nans
(other
, context
)
2572 c
= self
._cmp
(other
)
2574 # If both operands are finite and equal in numerical value
2575 # then an ordering is applied:
2577 # If the signs differ then max returns the operand with the
2578 # positive sign and min returns the operand with the negative sign
2580 # If the signs are the same then the exponent is used to select
2581 # the result. This is exactly the ordering used in compare_total.
2582 c
= self
.compare_total(other
)
2589 return ans
._fix
(context
)
2591 def min(self
, other
, context
=None):
2592 """Returns the smaller value.
2594 Like min(self, other) except if one is not a number, returns
2595 NaN (and signals if one is sNaN). Also rounds.
2597 other
= _convert_other(other
, raiseit
=True)
2600 context
= getcontext()
2602 if self
._is
_special
or other
._is
_special
:
2603 # If one operand is a quiet NaN and the other is number, then the
2604 # number is always returned
2608 if on
== 1 and sn
== 0:
2609 return self
._fix
(context
)
2610 if sn
== 1 and on
== 0:
2611 return other
._fix
(context
)
2612 return self
._check
_nans
(other
, context
)
2614 c
= self
._cmp
(other
)
2616 c
= self
.compare_total(other
)
2623 return ans
._fix
(context
)
2625 def _isinteger(self
):
2626 """Returns whether self is an integer"""
2627 if self
._is
_special
:
2631 rest
= self
._int
[self
._exp
:]
2632 return rest
== '0'*len(rest
)
2635 """Returns True if self is even. Assumes self is an integer."""
2636 if not self
or self
._exp
> 0:
2638 return self
._int
[-1+self
._exp
] in '02468'
2641 """Return the adjusted exponent of self"""
2643 return self
._exp
+ len(self
._int
) - 1
2644 # If NaN or Infinity, self._exp is string
2648 def canonical(self
, context
=None):
2649 """Returns the same Decimal object.
2651 As we do not have different encodings for the same number, the
2652 received object already is in its canonical form.
2656 def compare_signal(self
, other
, context
=None):
2657 """Compares self to the other operand numerically.
2659 It's pretty much like compare(), but all NaNs signal, with signaling
2660 NaNs taking precedence over quiet NaNs.
2662 other
= _convert_other(other
, raiseit
= True)
2663 ans
= self
._compare
_check
_nans
(other
, context
)
2666 return self
.compare(other
, context
=context
)
2668 def compare_total(self
, other
):
2669 """Compares self to other using the abstract representations.
2671 This is not like the standard compare, which use their numerical
2672 value. Note that a total ordering is defined for all possible abstract
2675 # if one is negative and the other is positive, it's easy
2676 if self
._sign
and not other
._sign
:
2678 if not self
._sign
and other
._sign
:
2682 # let's handle both NaN types
2683 self_nan
= self
._isnan
()
2684 other_nan
= other
._isnan
()
2685 if self_nan
or other_nan
:
2686 if self_nan
== other_nan
:
2687 if self
._int
< other
._int
:
2692 if self
._int
> other
._int
:
2723 if self
._exp
< other
._exp
:
2728 if self
._exp
> other
._exp
:
2736 def compare_total_mag(self
, other
):
2737 """Compares self to other using abstract repr., ignoring sign.
2739 Like compare_total, but with operand's sign ignored and assumed to be 0.
2742 o
= other
.copy_abs()
2743 return s
.compare_total(o
)
2746 """Returns a copy with the sign set to 0. """
2747 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
2749 def copy_negate(self
):
2750 """Returns a copy with the sign inverted."""
2752 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
2754 return _dec_from_triple(1, self
._int
, self
._exp
, self
._is
_special
)
2756 def copy_sign(self
, other
):
2757 """Returns self with the sign of other."""
2758 return _dec_from_triple(other
._sign
, self
._int
,
2759 self
._exp
, self
._is
_special
)
2761 def exp(self
, context
=None):
2762 """Returns e ** self."""
2765 context
= getcontext()
2768 ans
= self
._check
_nans
(context
=context
)
2772 # exp(-Infinity) = 0
2773 if self
._isinfinity
() == -1:
2780 # exp(Infinity) = Infinity
2781 if self
._isinfinity
() == 1:
2782 return Decimal(self
)
2784 # the result is now guaranteed to be inexact (the true
2785 # mathematical result is transcendental). There's no need to
2786 # raise Rounded and Inexact here---they'll always be raised as
2787 # a result of the call to _fix.
2789 adj
= self
.adjusted()
2791 # we only need to do any computation for quite a small range
2792 # of adjusted exponents---for example, -29 <= adj <= 10 for
2793 # the default context. For smaller exponent the result is
2794 # indistinguishable from 1 at the given precision, while for
2795 # larger exponent the result either overflows or underflows.
2796 if self
._sign
== 0 and adj
> len(str((context
.Emax
+1)*3)):
2798 ans
= _dec_from_triple(0, '1', context
.Emax
+1)
2799 elif self
._sign
== 1 and adj
> len(str((-context
.Etiny()+1)*3)):
2801 ans
= _dec_from_triple(0, '1', context
.Etiny()-1)
2802 elif self
._sign
== 0 and adj
< -p
:
2803 # p+1 digits; final round will raise correct flags
2804 ans
= _dec_from_triple(0, '1' + '0'*(p
-1) + '1', -p
)
2805 elif self
._sign
== 1 and adj
< -p
-1:
2806 # p+1 digits; final round will raise correct flags
2807 ans
= _dec_from_triple(0, '9'*(p
+1), -p
-1)
2811 c
, e
= op
.int, op
.exp
2815 # compute correctly rounded result: increase precision by
2816 # 3 digits at a time until we get an unambiguously
2820 coeff
, exp
= _dexp(c
, e
, p
+extra
)
2821 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
2825 ans
= _dec_from_triple(0, str(coeff
), exp
)
2827 # at this stage, ans should round correctly with *any*
2828 # rounding mode, not just with ROUND_HALF_EVEN
2829 context
= context
._shallow
_copy
()
2830 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2831 ans
= ans
._fix
(context
)
2832 context
.rounding
= rounding
2836 def is_canonical(self
):
2837 """Return True if self is canonical; otherwise return False.
2839 Currently, the encoding of a Decimal instance is always
2840 canonical, so this method returns True for any Decimal.
2844 def is_finite(self
):
2845 """Return True if self is finite; otherwise return False.
2847 A Decimal instance is considered finite if it is neither
2850 return not self
._is
_special
2852 def is_infinite(self
):
2853 """Return True if self is infinite; otherwise return False."""
2854 return self
._exp
== 'F'
2857 """Return True if self is a qNaN or sNaN; otherwise return False."""
2858 return self
._exp
in ('n', 'N')
2860 def is_normal(self
, context
=None):
2861 """Return True if self is a normal number; otherwise return False."""
2862 if self
._is
_special
or not self
:
2865 context
= getcontext()
2866 return context
.Emin
<= self
.adjusted() <= context
.Emax
2869 """Return True if self is a quiet NaN; otherwise return False."""
2870 return self
._exp
== 'n'
2872 def is_signed(self
):
2873 """Return True if self is negative; otherwise return False."""
2874 return self
._sign
== 1
2877 """Return True if self is a signaling NaN; otherwise return False."""
2878 return self
._exp
== 'N'
2880 def is_subnormal(self
, context
=None):
2881 """Return True if self is subnormal; otherwise return False."""
2882 if self
._is
_special
or not self
:
2885 context
= getcontext()
2886 return self
.adjusted() < context
.Emin
2889 """Return True if self is a zero; otherwise return False."""
2890 return not self
._is
_special
and self
._int
== '0'
2892 def _ln_exp_bound(self
):
2893 """Compute a lower bound for the adjusted exponent of self.ln().
2894 In other words, compute r such that self.ln() >= 10**r. Assumes
2895 that self is finite and positive and that self != 1.
2898 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2899 adj
= self
._exp
+ len(self
._int
) - 1
2901 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2902 return len(str(adj
*23//10)) - 1
2905 return len(str((-1-adj
)*23//10)) - 1
2907 c
, e
= op
.int, op
.exp
2912 return len(num
) - len(den
) - (num
< den
)
2913 # adj == -1, 0.1 <= self < 1
2914 return e
+ len(str(10**-e
- c
)) - 1
2917 def ln(self
, context
=None):
2918 """Returns the natural (base e) logarithm of self."""
2921 context
= getcontext()
2924 ans
= self
._check
_nans
(context
=context
)
2928 # ln(0.0) == -Infinity
2932 # ln(Infinity) = Infinity
2933 if self
._isinfinity
() == 1:
2940 # ln(negative) raises InvalidOperation
2942 return context
._raise
_error
(InvalidOperation
,
2943 'ln of a negative value')
2945 # result is irrational, so necessarily inexact
2947 c
, e
= op
.int, op
.exp
2950 # correctly rounded result: repeatedly increase precision by 3
2951 # until we get an unambiguously roundable result
2952 places
= p
- self
._ln
_exp
_bound
() + 2 # at least p+3 places
2954 coeff
= _dlog(c
, e
, places
)
2955 # assert len(str(abs(coeff)))-p >= 1
2956 if coeff
% (5*10**(len(str(abs(coeff
)))-p
-1)):
2959 ans
= _dec_from_triple(int(coeff
<0), str(abs(coeff
)), -places
)
2961 context
= context
._shallow
_copy
()
2962 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2963 ans
= ans
._fix
(context
)
2964 context
.rounding
= rounding
2967 def _log10_exp_bound(self
):
2968 """Compute a lower bound for the adjusted exponent of self.log10().
2969 In other words, find r such that self.log10() >= 10**r.
2970 Assumes that self is finite and positive and that self != 1.
2973 # For x >= 10 or x < 0.1 we only need a bound on the integer
2974 # part of log10(self), and this comes directly from the
2975 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2976 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2977 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2979 adj
= self
._exp
+ len(self
._int
) - 1
2982 return len(str(adj
))-1
2985 return len(str(-1-adj
))-1
2987 c
, e
= op
.int, op
.exp
2992 return len(num
) - len(den
) - (num
< den
) + 2
2993 # adj == -1, 0.1 <= self < 1
2995 return len(num
) + e
- (num
< "231") - 1
2997 def log10(self
, context
=None):
2998 """Returns the base 10 logarithm of self."""
3001 context
= getcontext()
3004 ans
= self
._check
_nans
(context
=context
)
3008 # log10(0.0) == -Infinity
3012 # log10(Infinity) = Infinity
3013 if self
._isinfinity
() == 1:
3016 # log10(negative or -Infinity) raises InvalidOperation
3018 return context
._raise
_error
(InvalidOperation
,
3019 'log10 of a negative value')
3022 if self
._int
[0] == '1' and self
._int
[1:] == '0'*(len(self
._int
) - 1):
3023 # answer may need rounding
3024 ans
= Decimal(self
._exp
+ len(self
._int
) - 1)
3026 # result is irrational, so necessarily inexact
3028 c
, e
= op
.int, op
.exp
3031 # correctly rounded result: repeatedly increase precision
3032 # until result is unambiguously roundable
3033 places
= p
-self
._log
10_exp
_bound
()+2
3035 coeff
= _dlog10(c
, e
, places
)
3036 # assert len(str(abs(coeff)))-p >= 1
3037 if coeff
% (5*10**(len(str(abs(coeff
)))-p
-1)):
3040 ans
= _dec_from_triple(int(coeff
<0), str(abs(coeff
)), -places
)
3042 context
= context
._shallow
_copy
()
3043 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
3044 ans
= ans
._fix
(context
)
3045 context
.rounding
= rounding
3048 def logb(self
, context
=None):
3049 """ Returns the exponent of the magnitude of self's MSD.
3051 The result is the integer which is the exponent of the magnitude
3052 of the most significant digit of self (as though it were truncated
3053 to a single digit while maintaining the value of that digit and
3054 without limiting the resulting exponent).
3057 ans
= self
._check
_nans
(context
=context
)
3062 context
= getcontext()
3064 # logb(+/-Inf) = +Inf
3065 if self
._isinfinity
():
3068 # logb(0) = -Inf, DivisionByZero
3070 return context
._raise
_error
(DivisionByZero
, 'logb(0)', 1)
3072 # otherwise, simply return the adjusted exponent of self, as a
3073 # Decimal. Note that no attempt is made to fit the result
3074 # into the current context.
3075 return Decimal(self
.adjusted())
3077 def _islogical(self
):
3078 """Return True if self is a logical operand.
3080 For being logical, it must be a finite number with a sign of 0,
3081 an exponent of 0, and a coefficient whose digits must all be
3084 if self
._sign
!= 0 or self
._exp
!= 0:
3086 for dig
in self
._int
:
3091 def _fill_logical(self
, context
, opa
, opb
):
3092 dif
= context
.prec
- len(opa
)
3096 opa
= opa
[-context
.prec
:]
3097 dif
= context
.prec
- len(opb
)
3101 opb
= opb
[-context
.prec
:]
3104 def logical_and(self
, other
, context
=None):
3105 """Applies an 'and' operation between self and other's digits."""
3107 context
= getcontext()
3108 if not self
._islogical
() or not other
._islogical
():
3109 return context
._raise
_error
(InvalidOperation
)
3111 # fill to context.prec
3112 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3114 # make the operation, and clean starting zeroes
3115 result
= "".join([str(int(a
)&int(b
)) for a
,b
in zip(opa
,opb
)])
3116 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3118 def logical_invert(self
, context
=None):
3119 """Invert all its digits."""
3121 context
= getcontext()
3122 return self
.logical_xor(_dec_from_triple(0,'1'*context
.prec
,0),
3125 def logical_or(self
, other
, context
=None):
3126 """Applies an 'or' operation between self and other's digits."""
3128 context
= getcontext()
3129 if not self
._islogical
() or not other
._islogical
():
3130 return context
._raise
_error
(InvalidOperation
)
3132 # fill to context.prec
3133 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3135 # make the operation, and clean starting zeroes
3136 result
= "".join(str(int(a
)|
int(b
)) for a
,b
in zip(opa
,opb
))
3137 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3139 def logical_xor(self
, other
, context
=None):
3140 """Applies an 'xor' operation between self and other's digits."""
3142 context
= getcontext()
3143 if not self
._islogical
() or not other
._islogical
():
3144 return context
._raise
_error
(InvalidOperation
)
3146 # fill to context.prec
3147 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3149 # make the operation, and clean starting zeroes
3150 result
= "".join(str(int(a
)^
int(b
)) for a
,b
in zip(opa
,opb
))
3151 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3153 def max_mag(self
, other
, context
=None):
3154 """Compares the values numerically with their sign ignored."""
3155 other
= _convert_other(other
, raiseit
=True)
3158 context
= getcontext()
3160 if self
._is
_special
or other
._is
_special
:
3161 # If one operand is a quiet NaN and the other is number, then the
3162 # number is always returned
3166 if on
== 1 and sn
== 0:
3167 return self
._fix
(context
)
3168 if sn
== 1 and on
== 0:
3169 return other
._fix
(context
)
3170 return self
._check
_nans
(other
, context
)
3172 c
= self
.copy_abs()._cmp
(other
.copy_abs())
3174 c
= self
.compare_total(other
)
3181 return ans
._fix
(context
)
3183 def min_mag(self
, other
, context
=None):
3184 """Compares the values numerically with their sign ignored."""
3185 other
= _convert_other(other
, raiseit
=True)
3188 context
= getcontext()
3190 if self
._is
_special
or other
._is
_special
:
3191 # If one operand is a quiet NaN and the other is number, then the
3192 # number is always returned
3196 if on
== 1 and sn
== 0:
3197 return self
._fix
(context
)
3198 if sn
== 1 and on
== 0:
3199 return other
._fix
(context
)
3200 return self
._check
_nans
(other
, context
)
3202 c
= self
.copy_abs()._cmp
(other
.copy_abs())
3204 c
= self
.compare_total(other
)
3211 return ans
._fix
(context
)
3213 def next_minus(self
, context
=None):
3214 """Returns the largest representable number smaller than itself."""
3216 context
= getcontext()
3218 ans
= self
._check
_nans
(context
=context
)
3222 if self
._isinfinity
() == -1:
3224 if self
._isinfinity
() == 1:
3225 return _dec_from_triple(0, '9'*context
.prec
, context
.Etop())
3227 context
= context
.copy()
3228 context
._set
_rounding
(ROUND_FLOOR
)
3229 context
._ignore
_all
_flags
()
3230 new_self
= self
._fix
(context
)
3231 if new_self
!= self
:
3233 return self
.__sub
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3236 def next_plus(self
, context
=None):
3237 """Returns the smallest representable number larger than itself."""
3239 context
= getcontext()
3241 ans
= self
._check
_nans
(context
=context
)
3245 if self
._isinfinity
() == 1:
3247 if self
._isinfinity
() == -1:
3248 return _dec_from_triple(1, '9'*context
.prec
, context
.Etop())
3250 context
= context
.copy()
3251 context
._set
_rounding
(ROUND_CEILING
)
3252 context
._ignore
_all
_flags
()
3253 new_self
= self
._fix
(context
)
3254 if new_self
!= self
:
3256 return self
.__add
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3259 def next_toward(self
, other
, context
=None):
3260 """Returns the number closest to self, in the direction towards other.
3262 The result is the closest representable number to self
3263 (excluding self) that is in the direction towards other,
3264 unless both have the same value. If the two operands are
3265 numerically equal, then the result is a copy of self with the
3266 sign set to be the same as the sign of other.
3268 other
= _convert_other(other
, raiseit
=True)
3271 context
= getcontext()
3273 ans
= self
._check
_nans
(other
, context
)
3277 comparison
= self
._cmp
(other
)
3279 return self
.copy_sign(other
)
3281 if comparison
== -1:
3282 ans
= self
.next_plus(context
)
3283 else: # comparison == 1
3284 ans
= self
.next_minus(context
)
3286 # decide which flags to raise using value of ans
3287 if ans
._isinfinity
():
3288 context
._raise
_error
(Overflow
,
3289 'Infinite result from next_toward',
3291 context
._raise
_error
(Rounded
)
3292 context
._raise
_error
(Inexact
)
3293 elif ans
.adjusted() < context
.Emin
:
3294 context
._raise
_error
(Underflow
)
3295 context
._raise
_error
(Subnormal
)
3296 context
._raise
_error
(Rounded
)
3297 context
._raise
_error
(Inexact
)
3298 # if precision == 1 then we don't raise Clamped for a
3301 context
._raise
_error
(Clamped
)
3305 def number_class(self
, context
=None):
3306 """Returns an indication of the class of self.
3308 The class is one of the following strings:
3324 inf
= self
._isinfinity
()
3335 context
= getcontext()
3336 if self
.is_subnormal(context
=context
):
3341 # just a normal, regular, boring number, :)
3348 """Just returns 10, as this is Decimal, :)"""
3351 def rotate(self
, other
, context
=None):
3352 """Returns a rotated copy of self, value-of-other times."""
3354 context
= getcontext()
3356 ans
= self
._check
_nans
(other
, context
)
3361 return context
._raise
_error
(InvalidOperation
)
3362 if not (-context
.prec
<= int(other
) <= context
.prec
):
3363 return context
._raise
_error
(InvalidOperation
)
3365 if self
._isinfinity
():
3366 return Decimal(self
)
3368 # get values, pad if necessary
3371 topad
= context
.prec
- len(rotdig
)
3373 rotdig
= '0'*topad
+ rotdig
3376 rotated
= rotdig
[torot
:] + rotdig
[:torot
]
3377 return _dec_from_triple(self
._sign
,
3378 rotated
.lstrip('0') or '0', self
._exp
)
3380 def scaleb (self
, other
, context
=None):
3381 """Returns self operand after adding the second value to its exp."""
3383 context
= getcontext()
3385 ans
= self
._check
_nans
(other
, context
)
3390 return context
._raise
_error
(InvalidOperation
)
3391 liminf
= -2 * (context
.Emax
+ context
.prec
)
3392 limsup
= 2 * (context
.Emax
+ context
.prec
)
3393 if not (liminf
<= int(other
) <= limsup
):
3394 return context
._raise
_error
(InvalidOperation
)
3396 if self
._isinfinity
():
3397 return Decimal(self
)
3399 d
= _dec_from_triple(self
._sign
, self
._int
, self
._exp
+ int(other
))
3403 def shift(self
, other
, context
=None):
3404 """Returns a shifted copy of self, value-of-other times."""
3406 context
= getcontext()
3408 ans
= self
._check
_nans
(other
, context
)
3413 return context
._raise
_error
(InvalidOperation
)
3414 if not (-context
.prec
<= int(other
) <= context
.prec
):
3415 return context
._raise
_error
(InvalidOperation
)
3417 if self
._isinfinity
():
3418 return Decimal(self
)
3420 # get values, pad if necessary
3423 return Decimal(self
)
3425 topad
= context
.prec
- len(rotdig
)
3427 rotdig
= '0'*topad
+ rotdig
3431 rotated
= rotdig
[:torot
]
3433 rotated
= rotdig
+ '0'*torot
3434 rotated
= rotated
[-context
.prec
:]
3436 return _dec_from_triple(self
._sign
,
3437 rotated
.lstrip('0') or '0', self
._exp
)
3439 # Support for pickling, copy, and deepcopy
3440 def __reduce__(self
):
3441 return (self
.__class
__, (str(self
),))
3444 if type(self
) == Decimal
:
3445 return self
# I'm immutable; therefore I am my own clone
3446 return self
.__class
__(str(self
))
3448 def __deepcopy__(self
, memo
):
3449 if type(self
) == Decimal
:
3450 return self
# My components are also immutable
3451 return self
.__class
__(str(self
))
3453 # PEP 3101 support. See also _parse_format_specifier and _format_align
3454 def __format__(self
, specifier
, context
=None):
3455 """Format a Decimal instance according to the given specifier.
3457 The specifier should be a standard format specifier, with the
3458 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3459 'F', 'g', 'G', and '%' are supported. If the formatting type
3460 is omitted it defaults to 'g' or 'G', depending on the value
3461 of context.capitals.
3463 At this time the 'n' format specifier type (which is supposed
3464 to use the current locale) is not supported.
3467 # Note: PEP 3101 says that if the type is not present then
3468 # there should be at least one digit after the decimal point.
3469 # We take the liberty of ignoring this requirement for
3470 # Decimal---it's presumably there to make sure that
3471 # format(float, '') behaves similarly to str(float).
3473 context
= getcontext()
3475 spec
= _parse_format_specifier(specifier
)
3477 # special values don't care about the type or precision...
3478 if self
._is
_special
:
3479 return _format_align(str(self
), spec
)
3481 # a type of None defaults to 'g' or 'G', depending on context
3482 # if type is '%', adjust exponent of self accordingly
3483 if spec
['type'] is None:
3484 spec
['type'] = ['g', 'G'][context
.capitals
]
3485 elif spec
['type'] == '%':
3486 self
= _dec_from_triple(self
._sign
, self
._int
, self
._exp
+2)
3488 # round if necessary, taking rounding mode from the context
3489 rounding
= context
.rounding
3490 precision
= spec
['precision']
3491 if precision
is not None:
3492 if spec
['type'] in 'eE':
3493 self
= self
._round
(precision
+1, rounding
)
3494 elif spec
['type'] in 'gG':
3495 if len(self
._int
) > precision
:
3496 self
= self
._round
(precision
, rounding
)
3497 elif spec
['type'] in 'fF%':
3498 self
= self
._rescale
(-precision
, rounding
)
3499 # special case: zeros with a positive exponent can't be
3500 # represented in fixed point; rescale them to 0e0.
3501 elif not self
and self
._exp
> 0 and spec
['type'] in 'fF%':
3502 self
= self
._rescale
(0, rounding
)
3504 # figure out placement of the decimal point
3505 leftdigits
= self
._exp
+ len(self
._int
)
3506 if spec
['type'] in 'fF%':
3507 dotplace
= leftdigits
3508 elif spec
['type'] in 'eE':
3509 if not self
and precision
is not None:
3510 dotplace
= 1 - precision
3513 elif spec
['type'] in 'gG':
3514 if self
._exp
<= 0 and leftdigits
> -6:
3515 dotplace
= leftdigits
3519 # figure out main part of numeric string...
3521 num
= '0.' + '0'*(-dotplace
) + self
._int
3522 elif dotplace
>= len(self
._int
):
3523 # make sure we're not padding a '0' with extra zeros on the right
3524 assert dotplace
==len(self
._int
) or self
._int
!= '0'
3525 num
= self
._int
+ '0'*(dotplace
-len(self
._int
))
3527 num
= self
._int
[:dotplace
] + '.' + self
._int
[dotplace
:]
3529 # ...then the trailing exponent, or trailing '%'
3530 if leftdigits
!= dotplace
or spec
['type'] in 'eE':
3531 echar
= {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec
['type']]
3532 num
= num
+ "{0}{1:+}".format(echar
, leftdigits
-dotplace
)
3533 elif spec
['type'] == '%':
3539 return _format_align(num
, spec
)
3542 def _dec_from_triple(sign
, coefficient
, exponent
, special
=False):
3543 """Create a decimal instance directly, without any validation,
3544 normalization (e.g. removal of leading zeros) or argument
3547 This function is for *internal use only*.
3550 self
= object.__new
__(Decimal
)
3552 self
._int
= coefficient
3553 self
._exp
= exponent
3554 self
._is
_special
= special
3558 ##### Context class #######################################################
3561 # get rounding method function:
3562 rounding_functions
= [name
for name
in Decimal
.__dict
__.keys()
3563 if name
.startswith('_round_')]
3564 for name
in rounding_functions
:
3565 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3566 globalname
= name
[1:].upper()
3567 val
= globals()[globalname
]
3568 Decimal
._pick
_rounding
_function
[val
] = name
3570 del name
, val
, globalname
, rounding_functions
3572 class _ContextManager(object):
3573 """Context manager class to support localcontext().
3575 Sets a copy of the supplied context in __enter__() and restores
3576 the previous decimal context in __exit__()
3578 def __init__(self
, new_context
):
3579 self
.new_context
= new_context
.copy()
3580 def __enter__(self
):
3581 self
.saved_context
= getcontext()
3582 setcontext(self
.new_context
)
3583 return self
.new_context
3584 def __exit__(self
, t
, v
, tb
):
3585 setcontext(self
.saved_context
)
3587 class Context(object):
3588 """Contains the context for a Decimal instance.
3591 prec - precision (for use in rounding, division, square roots..)
3592 rounding - rounding type (how you round)
3593 traps - If traps[exception] = 1, then the exception is
3594 raised when it is caused. Otherwise, a value is
3596 flags - When an exception is caused, flags[exception] is set.
3597 (Whether or not the trap_enabler is set)
3598 Should be reset by user of Decimal instance.
3599 Emin - Minimum exponent
3600 Emax - Maximum exponent
3601 capitals - If 1, 1*10^1 is printed as 1E+1.
3602 If 0, printed as 1e1
3603 _clamp - If 1, change exponents if too high (Default 0)
3606 def __init__(self
, prec
=None, rounding
=None,
3607 traps
=None, flags
=None,
3608 Emin
=None, Emax
=None,
3609 capitals
=None, _clamp
=0,
3610 _ignored_flags
=None):
3613 if _ignored_flags
is None:
3615 if not isinstance(flags
, dict):
3616 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
])
3621 for name
, val
in locals().items():
3623 setattr(self
, name
, _copy
.copy(getattr(DefaultContext
, name
)))
3625 setattr(self
, name
, val
)
3629 """Show the current context."""
3631 s
.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3632 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3634 names
= [f
.__name
__ for f
, v
in self
.flags
.items() if v
]
3635 s
.append('flags=[' + ', '.join(names
) + ']')
3636 names
= [t
.__name
__ for t
, v
in self
.traps
.items() if v
]
3637 s
.append('traps=[' + ', '.join(names
) + ']')
3638 return ', '.join(s
) + ')'
3640 def clear_flags(self
):
3641 """Reset all flags to zero"""
3642 for flag
in self
.flags
:
3643 self
.flags
[flag
] = 0
3645 def _shallow_copy(self
):
3646 """Returns a shallow copy from self."""
3647 nc
= Context(self
.prec
, self
.rounding
, self
.traps
,
3648 self
.flags
, self
.Emin
, self
.Emax
,
3649 self
.capitals
, self
._clamp
, self
._ignored
_flags
)
3653 """Returns a deep copy from self."""
3654 nc
= Context(self
.prec
, self
.rounding
, self
.traps
.copy(),
3655 self
.flags
.copy(), self
.Emin
, self
.Emax
,
3656 self
.capitals
, self
._clamp
, self
._ignored
_flags
)
3660 def _raise_error(self
, condition
, explanation
= None, *args
):
3663 If the flag is in _ignored_flags, returns the default response.
3664 Otherwise, it sets the flag, then, if the corresponding
3665 trap_enabler is set, it reaises the exception. Otherwise, it returns
3666 the default value after setting the flag.
3668 error
= _condition_map
.get(condition
, condition
)
3669 if error
in self
._ignored
_flags
:
3670 # Don't touch the flag
3671 return error().handle(self
, *args
)
3673 self
.flags
[error
] = 1
3674 if not self
.traps
[error
]:
3675 # The errors define how to handle themselves.
3676 return condition().handle(self
, *args
)
3678 # Errors should only be risked on copies of the context
3679 # self._ignored_flags = []
3680 raise error(explanation
)
3682 def _ignore_all_flags(self
):
3683 """Ignore all flags, if they are raised"""
3684 return self
._ignore
_flags
(*_signals
)
3686 def _ignore_flags(self
, *flags
):
3687 """Ignore the flags, if they are raised"""
3688 # Do not mutate-- This way, copies of a context leave the original
3690 self
._ignored
_flags
= (self
._ignored
_flags
+ list(flags
))
3693 def _regard_flags(self
, *flags
):
3694 """Stop ignoring the flags, if they are raised"""
3695 if flags
and isinstance(flags
[0], (tuple,list)):
3698 self
._ignored
_flags
.remove(flag
)
3700 # We inherit object.__hash__, so we must deny this explicitly
3704 """Returns Etiny (= Emin - prec + 1)"""
3705 return int(self
.Emin
- self
.prec
+ 1)
3708 """Returns maximum exponent (= Emax - prec + 1)"""
3709 return int(self
.Emax
- self
.prec
+ 1)
3711 def _set_rounding(self
, type):
3712 """Sets the rounding type.
3714 Sets the rounding type, and returns the current (previous)
3715 rounding type. Often used like:
3717 context = context.copy()
3718 # so you don't change the calling context
3719 # if an error occurs in the middle.
3720 rounding = context._set_rounding(ROUND_UP)
3721 val = self.__sub__(other, context=context)
3722 context._set_rounding(rounding)
3724 This will make it round up for that operation.
3726 rounding
= self
.rounding
3730 def create_decimal(self
, num
='0'):
3731 """Creates a new Decimal instance but using self as context.
3733 This method implements the to-number operation of the
3734 IBM Decimal specification."""
3736 if isinstance(num
, basestring
) and num
!= num
.strip():
3737 return self
._raise
_error
(ConversionSyntax
,
3738 "no trailing or leading whitespace is "
3741 d
= Decimal(num
, context
=self
)
3742 if d
._isnan
() and len(d
._int
) > self
.prec
- self
._clamp
:
3743 return self
._raise
_error
(ConversionSyntax
,
3744 "diagnostic info too long in NaN")
3749 """Returns the absolute value of the operand.
3751 If the operand is negative, the result is the same as using the minus
3752 operation on the operand. Otherwise, the result is the same as using
3753 the plus operation on the operand.
3755 >>> ExtendedContext.abs(Decimal('2.1'))
3757 >>> ExtendedContext.abs(Decimal('-100'))
3759 >>> ExtendedContext.abs(Decimal('101.5'))
3761 >>> ExtendedContext.abs(Decimal('-101.5'))
3764 return a
.__abs
__(context
=self
)
3766 def add(self
, a
, b
):
3767 """Return the sum of the two operands.
3769 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3771 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3774 return a
.__add
__(b
, context
=self
)
3776 def _apply(self
, a
):
3777 return str(a
._fix
(self
))
3779 def canonical(self
, a
):
3780 """Returns the same Decimal object.
3782 As we do not have different encodings for the same number, the
3783 received object already is in its canonical form.
3785 >>> ExtendedContext.canonical(Decimal('2.50'))
3788 return a
.canonical(context
=self
)
3790 def compare(self
, a
, b
):
3791 """Compares values numerically.
3793 If the signs of the operands differ, a value representing each operand
3794 ('-1' if the operand is less than zero, '0' if the operand is zero or
3795 negative zero, or '1' if the operand is greater than zero) is used in
3796 place of that operand for the comparison instead of the actual
3799 The comparison is then effected by subtracting the second operand from
3800 the first and then returning a value according to the result of the
3801 subtraction: '-1' if the result is less than zero, '0' if the result is
3802 zero or negative zero, or '1' if the result is greater than zero.
3804 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3806 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3808 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3810 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3812 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3814 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3817 return a
.compare(b
, context
=self
)
3819 def compare_signal(self
, a
, b
):
3820 """Compares the values of the two operands numerically.
3822 It's pretty much like compare(), but all NaNs signal, with signaling
3823 NaNs taking precedence over quiet NaNs.
3825 >>> c = ExtendedContext
3826 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3828 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3830 >>> c.flags[InvalidOperation] = 0
3831 >>> print c.flags[InvalidOperation]
3833 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3835 >>> print c.flags[InvalidOperation]
3837 >>> c.flags[InvalidOperation] = 0
3838 >>> print c.flags[InvalidOperation]
3840 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3842 >>> print c.flags[InvalidOperation]
3845 return a
.compare_signal(b
, context
=self
)
3847 def compare_total(self
, a
, b
):
3848 """Compares two operands using their abstract representation.
3850 This is not like the standard compare, which use their numerical
3851 value. Note that a total ordering is defined for all possible abstract
3854 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3856 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3858 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3860 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3862 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3864 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3867 return a
.compare_total(b
)
3869 def compare_total_mag(self
, a
, b
):
3870 """Compares two operands using their abstract representation ignoring sign.
3872 Like compare_total, but with operand's sign ignored and assumed to be 0.
3874 return a
.compare_total_mag(b
)
3876 def copy_abs(self
, a
):
3877 """Returns a copy of the operand with the sign set to 0.
3879 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3881 >>> ExtendedContext.copy_abs(Decimal('-100'))
3886 def copy_decimal(self
, a
):
3887 """Returns a copy of the decimal objet.
3889 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3891 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3896 def copy_negate(self
, a
):
3897 """Returns a copy of the operand with the sign inverted.
3899 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3901 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3904 return a
.copy_negate()
3906 def copy_sign(self
, a
, b
):
3907 """Copies the second operand's sign to the first one.
3909 In detail, it returns a copy of the first operand with the sign
3910 equal to the sign of the second operand.
3912 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3914 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3916 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3918 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3921 return a
.copy_sign(b
)
3923 def divide(self
, a
, b
):
3924 """Decimal division in a specified context.
3926 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3927 Decimal('0.333333333')
3928 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3929 Decimal('0.666666667')
3930 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3932 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3934 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3936 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3938 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3940 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3942 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3944 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3947 return a
.__div
__(b
, context
=self
)
3949 def divide_int(self
, a
, b
):
3950 """Divides two numbers and returns the integer part of the result.
3952 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3954 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3956 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3959 return a
.__floordiv
__(b
, context
=self
)
3961 def divmod(self
, a
, b
):
3962 return a
.__divmod
__(b
, context
=self
)
3967 >>> c = ExtendedContext.copy()
3970 >>> c.exp(Decimal('-Infinity'))
3972 >>> c.exp(Decimal('-1'))
3973 Decimal('0.367879441')
3974 >>> c.exp(Decimal('0'))
3976 >>> c.exp(Decimal('1'))
3977 Decimal('2.71828183')
3978 >>> c.exp(Decimal('0.693147181'))
3979 Decimal('2.00000000')
3980 >>> c.exp(Decimal('+Infinity'))
3983 return a
.exp(context
=self
)
3985 def fma(self
, a
, b
, c
):
3986 """Returns a multiplied by b, plus c.
3988 The first two operands are multiplied together, using multiply,
3989 the third operand is then added to the result of that
3990 multiplication, using add, all with only one final rounding.
3992 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3994 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3996 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3997 Decimal('1.38435736E+12')
3999 return a
.fma(b
, c
, context
=self
)
4001 def is_canonical(self
, a
):
4002 """Return True if the operand is canonical; otherwise return False.
4004 Currently, the encoding of a Decimal instance is always
4005 canonical, so this method returns True for any Decimal.
4007 >>> ExtendedContext.is_canonical(Decimal('2.50'))
4010 return a
.is_canonical()
4012 def is_finite(self
, a
):
4013 """Return True if the operand is finite; otherwise return False.
4015 A Decimal instance is considered finite if it is neither
4018 >>> ExtendedContext.is_finite(Decimal('2.50'))
4020 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4022 >>> ExtendedContext.is_finite(Decimal('0'))
4024 >>> ExtendedContext.is_finite(Decimal('Inf'))
4026 >>> ExtendedContext.is_finite(Decimal('NaN'))
4029 return a
.is_finite()
4031 def is_infinite(self
, a
):
4032 """Return True if the operand is infinite; otherwise return False.
4034 >>> ExtendedContext.is_infinite(Decimal('2.50'))
4036 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4038 >>> ExtendedContext.is_infinite(Decimal('NaN'))
4041 return a
.is_infinite()
4043 def is_nan(self
, a
):
4044 """Return True if the operand is a qNaN or sNaN;
4045 otherwise return False.
4047 >>> ExtendedContext.is_nan(Decimal('2.50'))
4049 >>> ExtendedContext.is_nan(Decimal('NaN'))
4051 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4056 def is_normal(self
, a
):
4057 """Return True if the operand is a normal number;
4058 otherwise return False.
4060 >>> c = ExtendedContext.copy()
4063 >>> c.is_normal(Decimal('2.50'))
4065 >>> c.is_normal(Decimal('0.1E-999'))
4067 >>> c.is_normal(Decimal('0.00'))
4069 >>> c.is_normal(Decimal('-Inf'))
4071 >>> c.is_normal(Decimal('NaN'))
4074 return a
.is_normal(context
=self
)
4076 def is_qnan(self
, a
):
4077 """Return True if the operand is a quiet NaN; otherwise return False.
4079 >>> ExtendedContext.is_qnan(Decimal('2.50'))
4081 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4083 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4088 def is_signed(self
, a
):
4089 """Return True if the operand is negative; otherwise return False.
4091 >>> ExtendedContext.is_signed(Decimal('2.50'))
4093 >>> ExtendedContext.is_signed(Decimal('-12'))
4095 >>> ExtendedContext.is_signed(Decimal('-0'))
4098 return a
.is_signed()
4100 def is_snan(self
, a
):
4101 """Return True if the operand is a signaling NaN;
4102 otherwise return False.
4104 >>> ExtendedContext.is_snan(Decimal('2.50'))
4106 >>> ExtendedContext.is_snan(Decimal('NaN'))
4108 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4113 def is_subnormal(self
, a
):
4114 """Return True if the operand is subnormal; otherwise return False.
4116 >>> c = ExtendedContext.copy()
4119 >>> c.is_subnormal(Decimal('2.50'))
4121 >>> c.is_subnormal(Decimal('0.1E-999'))
4123 >>> c.is_subnormal(Decimal('0.00'))
4125 >>> c.is_subnormal(Decimal('-Inf'))
4127 >>> c.is_subnormal(Decimal('NaN'))
4130 return a
.is_subnormal(context
=self
)
4132 def is_zero(self
, a
):
4133 """Return True if the operand is a zero; otherwise return False.
4135 >>> ExtendedContext.is_zero(Decimal('0'))
4137 >>> ExtendedContext.is_zero(Decimal('2.50'))
4139 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4145 """Returns the natural (base e) logarithm of the operand.
4147 >>> c = ExtendedContext.copy()
4150 >>> c.ln(Decimal('0'))
4151 Decimal('-Infinity')
4152 >>> c.ln(Decimal('1.000'))
4154 >>> c.ln(Decimal('2.71828183'))
4155 Decimal('1.00000000')
4156 >>> c.ln(Decimal('10'))
4157 Decimal('2.30258509')
4158 >>> c.ln(Decimal('+Infinity'))
4161 return a
.ln(context
=self
)
4164 """Returns the base 10 logarithm of the operand.
4166 >>> c = ExtendedContext.copy()
4169 >>> c.log10(Decimal('0'))
4170 Decimal('-Infinity')
4171 >>> c.log10(Decimal('0.001'))
4173 >>> c.log10(Decimal('1.000'))
4175 >>> c.log10(Decimal('2'))
4176 Decimal('0.301029996')
4177 >>> c.log10(Decimal('10'))
4179 >>> c.log10(Decimal('70'))
4180 Decimal('1.84509804')
4181 >>> c.log10(Decimal('+Infinity'))
4184 return a
.log10(context
=self
)
4187 """ Returns the exponent of the magnitude of the operand's MSD.
4189 The result is the integer which is the exponent of the magnitude
4190 of the most significant digit of the operand (as though the
4191 operand were truncated to a single digit while maintaining the
4192 value of that digit and without limiting the resulting exponent).
4194 >>> ExtendedContext.logb(Decimal('250'))
4196 >>> ExtendedContext.logb(Decimal('2.50'))
4198 >>> ExtendedContext.logb(Decimal('0.03'))
4200 >>> ExtendedContext.logb(Decimal('0'))
4201 Decimal('-Infinity')
4203 return a
.logb(context
=self
)
4205 def logical_and(self
, a
, b
):
4206 """Applies the logical operation 'and' between each operand's digits.
4208 The operands must be both logical numbers.
4210 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4212 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4214 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4216 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4218 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4220 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4223 return a
.logical_and(b
, context
=self
)
4225 def logical_invert(self
, a
):
4226 """Invert all the digits in the operand.
4228 The operand must be a logical number.
4230 >>> ExtendedContext.logical_invert(Decimal('0'))
4231 Decimal('111111111')
4232 >>> ExtendedContext.logical_invert(Decimal('1'))
4233 Decimal('111111110')
4234 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4236 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4239 return a
.logical_invert(context
=self
)
4241 def logical_or(self
, a
, b
):
4242 """Applies the logical operation 'or' between each operand's digits.
4244 The operands must be both logical numbers.
4246 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4248 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4250 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4252 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4254 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4256 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4259 return a
.logical_or(b
, context
=self
)
4261 def logical_xor(self
, a
, b
):
4262 """Applies the logical operation 'xor' between each operand's digits.
4264 The operands must be both logical numbers.
4266 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4268 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4270 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4272 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4274 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4276 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4279 return a
.logical_xor(b
, context
=self
)
4282 """max compares two values numerically and returns the maximum.
4284 If either operand is a NaN then the general rules apply.
4285 Otherwise, the operands are compared as though by the compare
4286 operation. If they are numerically equal then the left-hand operand
4287 is chosen as the result. Otherwise the maximum (closer to positive
4288 infinity) of the two operands is chosen as the result.
4290 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4292 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4294 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4296 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4299 return a
.max(b
, context
=self
)
4301 def max_mag(self
, a
, b
):
4302 """Compares the values numerically with their sign ignored."""
4303 return a
.max_mag(b
, context
=self
)
4306 """min compares two values numerically and returns the minimum.
4308 If either operand is a NaN then the general rules apply.
4309 Otherwise, the operands are compared as though by the compare
4310 operation. If they are numerically equal then the left-hand operand
4311 is chosen as the result. Otherwise the minimum (closer to negative
4312 infinity) of the two operands is chosen as the result.
4314 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4316 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4318 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4320 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4323 return a
.min(b
, context
=self
)
4325 def min_mag(self
, a
, b
):
4326 """Compares the values numerically with their sign ignored."""
4327 return a
.min_mag(b
, context
=self
)
4330 """Minus corresponds to unary prefix minus in Python.
4332 The operation is evaluated using the same rules as subtract; the
4333 operation minus(a) is calculated as subtract('0', a) where the '0'
4334 has the same exponent as the operand.
4336 >>> ExtendedContext.minus(Decimal('1.3'))
4338 >>> ExtendedContext.minus(Decimal('-1.3'))
4341 return a
.__neg
__(context
=self
)
4343 def multiply(self
, a
, b
):
4344 """multiply multiplies two operands.
4346 If either operand is a special value then the general rules apply.
4347 Otherwise, the operands are multiplied together ('long multiplication'),
4348 resulting in a number which may be as long as the sum of the lengths
4349 of the two operands.
4351 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4353 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4355 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4357 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4359 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4360 Decimal('4.28135971E+11')
4362 return a
.__mul
__(b
, context
=self
)
4364 def next_minus(self
, a
):
4365 """Returns the largest representable number smaller than a.
4367 >>> c = ExtendedContext.copy()
4370 >>> ExtendedContext.next_minus(Decimal('1'))
4371 Decimal('0.999999999')
4372 >>> c.next_minus(Decimal('1E-1007'))
4374 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4375 Decimal('-1.00000004')
4376 >>> c.next_minus(Decimal('Infinity'))
4377 Decimal('9.99999999E+999')
4379 return a
.next_minus(context
=self
)
4381 def next_plus(self
, a
):
4382 """Returns the smallest representable number larger than a.
4384 >>> c = ExtendedContext.copy()
4387 >>> ExtendedContext.next_plus(Decimal('1'))
4388 Decimal('1.00000001')
4389 >>> c.next_plus(Decimal('-1E-1007'))
4391 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4392 Decimal('-1.00000002')
4393 >>> c.next_plus(Decimal('-Infinity'))
4394 Decimal('-9.99999999E+999')
4396 return a
.next_plus(context
=self
)
4398 def next_toward(self
, a
, b
):
4399 """Returns the number closest to a, in direction towards b.
4401 The result is the closest representable number from the first
4402 operand (but not the first operand) that is in the direction
4403 towards the second operand, unless the operands have the same
4406 >>> c = ExtendedContext.copy()
4409 >>> c.next_toward(Decimal('1'), Decimal('2'))
4410 Decimal('1.00000001')
4411 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4413 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4414 Decimal('-1.00000002')
4415 >>> c.next_toward(Decimal('1'), Decimal('0'))
4416 Decimal('0.999999999')
4417 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4419 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4420 Decimal('-1.00000004')
4421 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4424 return a
.next_toward(b
, context
=self
)
4426 def normalize(self
, a
):
4427 """normalize reduces an operand to its simplest form.
4429 Essentially a plus operation with all trailing zeros removed from the
4432 >>> ExtendedContext.normalize(Decimal('2.1'))
4434 >>> ExtendedContext.normalize(Decimal('-2.0'))
4436 >>> ExtendedContext.normalize(Decimal('1.200'))
4438 >>> ExtendedContext.normalize(Decimal('-120'))
4440 >>> ExtendedContext.normalize(Decimal('120.00'))
4442 >>> ExtendedContext.normalize(Decimal('0.00'))
4445 return a
.normalize(context
=self
)
4447 def number_class(self
, a
):
4448 """Returns an indication of the class of the operand.
4450 The class is one of the following strings:
4462 >>> c = Context(ExtendedContext)
4465 >>> c.number_class(Decimal('Infinity'))
4467 >>> c.number_class(Decimal('1E-10'))
4469 >>> c.number_class(Decimal('2.50'))
4471 >>> c.number_class(Decimal('0.1E-999'))
4473 >>> c.number_class(Decimal('0'))
4475 >>> c.number_class(Decimal('-0'))
4477 >>> c.number_class(Decimal('-0.1E-999'))
4479 >>> c.number_class(Decimal('-1E-10'))
4481 >>> c.number_class(Decimal('-2.50'))
4483 >>> c.number_class(Decimal('-Infinity'))
4485 >>> c.number_class(Decimal('NaN'))
4487 >>> c.number_class(Decimal('-NaN'))
4489 >>> c.number_class(Decimal('sNaN'))
4492 return a
.number_class(context
=self
)
4495 """Plus corresponds to unary prefix plus in Python.
4497 The operation is evaluated using the same rules as add; the
4498 operation plus(a) is calculated as add('0', a) where the '0'
4499 has the same exponent as the operand.
4501 >>> ExtendedContext.plus(Decimal('1.3'))
4503 >>> ExtendedContext.plus(Decimal('-1.3'))
4506 return a
.__pos
__(context
=self
)
4508 def power(self
, a
, b
, modulo
=None):
4509 """Raises a to the power of b, to modulo if given.
4511 With two arguments, compute a**b. If a is negative then b
4512 must be integral. The result will be inexact unless b is
4513 integral and the result is finite and can be expressed exactly
4514 in 'precision' digits.
4516 With three arguments, compute (a**b) % modulo. For the
4517 three argument form, the following restrictions on the
4520 - all three arguments must be integral
4521 - b must be nonnegative
4522 - at least one of a or b must be nonzero
4523 - modulo must be nonzero and have at most 'precision' digits
4525 The result of pow(a, b, modulo) is identical to the result
4526 that would be obtained by computing (a**b) % modulo with
4527 unbounded precision, but is computed more efficiently. It is
4530 >>> c = ExtendedContext.copy()
4533 >>> c.power(Decimal('2'), Decimal('3'))
4535 >>> c.power(Decimal('-2'), Decimal('3'))
4537 >>> c.power(Decimal('2'), Decimal('-3'))
4539 >>> c.power(Decimal('1.7'), Decimal('8'))
4540 Decimal('69.7575744')
4541 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4542 Decimal('2.00000000')
4543 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4545 >>> c.power(Decimal('Infinity'), Decimal('0'))
4547 >>> c.power(Decimal('Infinity'), Decimal('1'))
4549 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4551 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4553 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4554 Decimal('-Infinity')
4555 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4557 >>> c.power(Decimal('0'), Decimal('0'))
4560 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4562 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4564 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4566 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4568 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4570 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4572 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4575 return a
.__pow
__(b
, modulo
, context
=self
)
4577 def quantize(self
, a
, b
):
4578 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4580 The coefficient of the result is derived from that of the left-hand
4581 operand. It may be rounded using the current rounding setting (if the
4582 exponent is being increased), multiplied by a positive power of ten (if
4583 the exponent is being decreased), or is unchanged (if the exponent is
4584 already equal to that of the right-hand operand).
4586 Unlike other operations, if the length of the coefficient after the
4587 quantize operation would be greater than precision then an Invalid
4588 operation condition is raised. This guarantees that, unless there is
4589 an error condition, the exponent of the result of a quantize is always
4590 equal to that of the right-hand operand.
4592 Also unlike other operations, quantize will never raise Underflow, even
4593 if the result is subnormal and inexact.
4595 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4597 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4599 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4601 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4603 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4605 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4606 Decimal('-Infinity')
4607 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4609 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4611 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4613 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4615 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4617 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4619 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4621 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4623 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4626 return a
.quantize(b
, context
=self
)
4629 """Just returns 10, as this is Decimal, :)
4631 >>> ExtendedContext.radix()
4636 def remainder(self
, a
, b
):
4637 """Returns the remainder from integer division.
4639 The result is the residue of the dividend after the operation of
4640 calculating integer division as described for divide-integer, rounded
4641 to precision digits if necessary. The sign of the result, if
4642 non-zero, is the same as that of the original dividend.
4644 This operation will fail under the same conditions as integer division
4645 (that is, if integer division on the same two operands would fail, the
4646 remainder cannot be calculated).
4648 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4650 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4652 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4654 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4656 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4658 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4661 return a
.__mod
__(b
, context
=self
)
4663 def remainder_near(self
, a
, b
):
4664 """Returns to be "a - b * n", where n is the integer nearest the exact
4665 value of "x / b" (if two integers are equally near then the even one
4666 is chosen). If the result is equal to 0 then its sign will be the
4669 This operation will fail under the same conditions as integer division
4670 (that is, if integer division on the same two operands would fail, the
4671 remainder cannot be calculated).
4673 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4675 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4677 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4679 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4681 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4683 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4685 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4688 return a
.remainder_near(b
, context
=self
)
4690 def rotate(self
, a
, b
):
4691 """Returns a rotated copy of a, b times.
4693 The coefficient of the result is a rotated copy of the digits in
4694 the coefficient of the first operand. The number of places of
4695 rotation is taken from the absolute value of the second operand,
4696 with the rotation being to the left if the second operand is
4697 positive or to the right otherwise.
4699 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4700 Decimal('400000003')
4701 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4703 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4704 Decimal('891234567')
4705 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4706 Decimal('123456789')
4707 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4708 Decimal('345678912')
4710 return a
.rotate(b
, context
=self
)
4712 def same_quantum(self
, a
, b
):
4713 """Returns True if the two operands have the same exponent.
4715 The result is never affected by either the sign or the coefficient of
4718 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4720 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4722 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4724 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4727 return a
.same_quantum(b
)
4729 def scaleb (self
, a
, b
):
4730 """Returns the first operand after adding the second value its exp.
4732 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4734 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4736 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4739 return a
.scaleb (b
, context
=self
)
4741 def shift(self
, a
, b
):
4742 """Returns a shifted copy of a, b times.
4744 The coefficient of the result is a shifted copy of the digits
4745 in the coefficient of the first operand. The number of places
4746 to shift is taken from the absolute value of the second operand,
4747 with the shift being to the left if the second operand is
4748 positive or to the right otherwise. Digits shifted into the
4749 coefficient are zeros.
4751 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4752 Decimal('400000000')
4753 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4755 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4757 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4758 Decimal('123456789')
4759 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4760 Decimal('345678900')
4762 return a
.shift(b
, context
=self
)
4765 """Square root of a non-negative number to context precision.
4767 If the result must be inexact, it is rounded using the round-half-even
4770 >>> ExtendedContext.sqrt(Decimal('0'))
4772 >>> ExtendedContext.sqrt(Decimal('-0'))
4774 >>> ExtendedContext.sqrt(Decimal('0.39'))
4775 Decimal('0.624499800')
4776 >>> ExtendedContext.sqrt(Decimal('100'))
4778 >>> ExtendedContext.sqrt(Decimal('1'))
4780 >>> ExtendedContext.sqrt(Decimal('1.0'))
4782 >>> ExtendedContext.sqrt(Decimal('1.00'))
4784 >>> ExtendedContext.sqrt(Decimal('7'))
4785 Decimal('2.64575131')
4786 >>> ExtendedContext.sqrt(Decimal('10'))
4787 Decimal('3.16227766')
4788 >>> ExtendedContext.prec
4791 return a
.sqrt(context
=self
)
4793 def subtract(self
, a
, b
):
4794 """Return the difference between the two operands.
4796 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4798 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4800 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4803 return a
.__sub
__(b
, context
=self
)
4805 def to_eng_string(self
, a
):
4806 """Converts a number to a string, using scientific notation.
4808 The operation is not affected by the context.
4810 return a
.to_eng_string(context
=self
)
4812 def to_sci_string(self
, a
):
4813 """Converts a number to a string, using scientific notation.
4815 The operation is not affected by the context.
4817 return a
.__str
__(context
=self
)
4819 def to_integral_exact(self
, a
):
4820 """Rounds to an integer.
4822 When the operand has a negative exponent, the result is the same
4823 as using the quantize() operation using the given operand as the
4824 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4825 of the operand as the precision setting; Inexact and Rounded flags
4826 are allowed in this operation. The rounding mode is taken from the
4829 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4831 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4833 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4835 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4837 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4839 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4841 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4843 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4844 Decimal('-Infinity')
4846 return a
.to_integral_exact(context
=self
)
4848 def to_integral_value(self
, a
):
4849 """Rounds to an integer.
4851 When the operand has a negative exponent, the result is the same
4852 as using the quantize() operation using the given operand as the
4853 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4854 of the operand as the precision setting, except that no flags will
4855 be set. The rounding mode is taken from the context.
4857 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4859 >>> ExtendedContext.to_integral_value(Decimal('100'))
4861 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4863 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4865 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4867 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4869 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4871 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4872 Decimal('-Infinity')
4874 return a
.to_integral_value(context
=self
)
4876 # the method name changed, but we provide also the old one, for compatibility
4877 to_integral
= to_integral_value
4879 class _WorkRep(object):
4880 __slots__
= ('sign','int','exp')
4883 # exp: None, int, or string
4885 def __init__(self
, value
=None):
4890 elif isinstance(value
, Decimal
):
4891 self
.sign
= value
._sign
4892 self
.int = int(value
._int
)
4893 self
.exp
= value
._exp
4895 # assert isinstance(value, tuple)
4896 self
.sign
= value
[0]
4901 return "(%r, %r, %r)" % (self
.sign
, self
.int, self
.exp
)
4907 def _normalize(op1
, op2
, prec
= 0):
4908 """Normalizes op1, op2 to have the same exp and length of coefficient.
4910 Done during addition.
4912 if op1
.exp
< op2
.exp
:
4919 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4920 # Then adding 10**exp to tmp has the same effect (after rounding)
4921 # as adding any positive quantity smaller than 10**exp; similarly
4922 # for subtraction. So if other is smaller than 10**exp we replace
4923 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4924 tmp_len
= len(str(tmp
.int))
4925 other_len
= len(str(other
.int))
4926 exp
= tmp
.exp
+ min(-1, tmp_len
- prec
- 2)
4927 if other_len
+ other
.exp
- 1 < exp
:
4931 tmp
.int *= 10 ** (tmp
.exp
- other
.exp
)
4935 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4937 # This function from Tim Peters was taken from here:
4938 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4939 # The correction being in the function definition is for speed, and
4940 # the whole function is not resolved with math.log because of avoiding
4941 # the use of floats.
4942 def _nbits(n
, correction
= {
4943 '0': 4, '1': 3, '2': 2, '3': 2,
4944 '4': 1, '5': 1, '6': 1, '7': 1,
4945 '8': 0, '9': 0, 'a': 0, 'b': 0,
4946 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4947 """Number of bits in binary representation of the positive integer n,
4951 raise ValueError("The argument to _nbits should be nonnegative.")
4953 return 4*len(hex_n
) - correction
[hex_n
[0]]
4955 def _sqrt_nearest(n
, a
):
4956 """Closest integer to the square root of the positive integer n. a is
4957 an initial approximation to the square root. Any positive integer
4958 will do for a, but the closer a is to the square root of n the
4959 faster convergence will be.
4962 if n
<= 0 or a
<= 0:
4963 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4967 b
, a
= a
, a
--n
//a
>>1
4970 def _rshift_nearest(x
, shift
):
4971 """Given an integer x and a nonnegative integer shift, return closest
4972 integer to x / 2**shift; use round-to-even in case of a tie.
4975 b
, q
= 1L << shift
, x
>> shift
4976 return q
+ (2*(x
& (b
-1)) + (q
&1) > b
)
4978 def _div_nearest(a
, b
):
4979 """Closest integer to a/b, a and b positive integers; rounds to even
4980 in the case of a tie.
4984 return q
+ (2*r
+ (q
&1) > b
)
4986 def _ilog(x
, M
, L
= 8):
4987 """Integer approximation to M*log(x/M), with absolute error boundable
4988 in terms only of x/M.
4990 Given positive integers x and M, return an integer approximation to
4991 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4992 between the approximation and the exact result is at most 22. For
4993 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4994 both cases these are upper bounds on the error; it will usually be
4997 # The basic algorithm is the following: let log1p be the function
4998 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5001 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5003 # repeatedly until the argument to log1p is small (< 2**-L in
5004 # absolute value). For small y we can use the Taylor series
5007 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5009 # truncating at T such that y**T is small enough. The whole
5010 # computation is carried out in a form of fixed-point arithmetic,
5011 # with a real number z being represented by an integer
5012 # approximation to z*M. To avoid loss of precision, the y below
5013 # is actually an integer approximation to 2**R*y*M, where R is the
5014 # number of reductions performed so far.
5017 # argument reduction; R = number of reductions performed
5019 while (R
<= L
and long(abs(y
)) << L
-R
>= M
or
5020 R
> L
and abs(y
) >> R
-L
>= M
):
5021 y
= _div_nearest(long(M
*y
) << 1,
5022 M
+ _sqrt_nearest(M
*(M
+_rshift_nearest(y
, R
)), M
))
5025 # Taylor series with T terms
5026 T
= -int(-10*len(str(M
))//(3*L
))
5027 yshift
= _rshift_nearest(y
, R
)
5028 w
= _div_nearest(M
, T
)
5029 for k
in xrange(T
-1, 0, -1):
5030 w
= _div_nearest(M
, k
) - _div_nearest(yshift
*w
, M
)
5032 return _div_nearest(w
*y
, M
)
5034 def _dlog10(c
, e
, p
):
5035 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5036 approximation to 10**p * log10(c*10**e), with an absolute error of
5037 at most 1. Assumes that c*10**e is not exactly 1."""
5039 # increase precision by 2; compensate for this by dividing
5040 # final result by 100
5043 # write c*10**e as d*10**f with either:
5044 # f >= 0 and 1 <= d <= 10, or
5045 # f <= 0 and 0.1 <= d <= 1.
5046 # Thus for c*10**e close to 1, f = 0
5048 f
= e
+l
- (e
+l
>= 1)
5056 c
= _div_nearest(c
, 10**-k
)
5058 log_d
= _ilog(c
, M
) # error < 5 + 22 = 27
5059 log_10
= _log10_digits(p
) # error < 1
5060 log_d
= _div_nearest(log_d
*M
, log_10
)
5061 log_tenpower
= f
*M
# exact
5063 log_d
= 0 # error < 2.31
5064 log_tenpower
= _div_nearest(f
, 10**-p
) # error < 0.5
5066 return _div_nearest(log_tenpower
+log_d
, 100)
5069 """Given integers c, e and p with c > 0, compute an integer
5070 approximation to 10**p * log(c*10**e), with an absolute error of
5071 at most 1. Assumes that c*10**e is not exactly 1."""
5073 # Increase precision by 2. The precision increase is compensated
5074 # for at the end with a division by 100.
5077 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5078 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5079 # as 10**p * log(d) + 10**p*f * log(10).
5081 f
= e
+l
- (e
+l
>= 1)
5083 # compute approximation to 10**p*log(d), with error < 27
5089 c
= _div_nearest(c
, 10**-k
) # error of <= 0.5 in c
5091 # _ilog magnifies existing error in c by a factor of at most 10
5092 log_d
= _ilog(c
, 10**p
) # error < 5 + 22 = 27
5094 # p <= 0: just approximate the whole thing by 0; error < 2.31
5097 # compute approximation to f*10**p*log(10), with error < 11.
5099 extra
= len(str(abs(f
)))-1
5101 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5102 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5103 f_log_ten
= _div_nearest(f
*_log10_digits(p
+extra
), 10**extra
)
5109 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5110 return _div_nearest(f_log_ten
+ log_d
, 100)
5112 class _Log10Memoize(object):
5113 """Class to compute, store, and allow retrieval of, digits of the
5114 constant log(10) = 2.302585.... This constant is needed by
5115 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5117 self
.digits
= "23025850929940456840179914546843642076011014886"
5119 def getdigits(self
, p
):
5120 """Given an integer p >= 0, return floor(10**p)*log(10).
5122 For example, self.getdigits(3) returns 2302.
5124 # digits are stored as a string, for quick conversion to
5125 # integer in the case that we've already computed enough
5126 # digits; the stored digits should always be correct
5127 # (truncated, not rounded to nearest).
5129 raise ValueError("p should be nonnegative")
5131 if p
>= len(self
.digits
):
5132 # compute p+3, p+6, p+9, ... digits; continue until at
5133 # least one of the extra digits is nonzero
5136 # compute p+extra digits, correct to within 1ulp
5138 digits
= str(_div_nearest(_ilog(10*M
, M
), 100))
5139 if digits
[-extra
:] != '0'*extra
:
5142 # keep all reliable digits so far; remove trailing zeros
5143 # and next nonzero digit
5144 self
.digits
= digits
.rstrip('0')[:-1]
5145 return int(self
.digits
[:p
+1])
5147 _log10_digits
= _Log10Memoize().getdigits
5149 def _iexp(x
, M
, L
=8):
5150 """Given integers x and M, M > 0, such that x/M is small in absolute
5151 value, compute an integer approximation to M*exp(x/M). For 0 <=
5152 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5153 is usually much smaller)."""
5155 # Algorithm: to compute exp(z) for a real number z, first divide z
5156 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5157 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5160 # expm1(x) = x + x**2/2! + x**3/3! + ...
5162 # Now use the identity
5164 # expm1(2x) = expm1(x)*(expm1(x)+2)
5166 # R times to compute the sequence expm1(z/2**R),
5167 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5169 # Find R such that x/2**R/M <= 2**-L
5170 R
= _nbits((long(x
)<<L
)//M
)
5172 # Taylor series. (2**L)**T > M
5173 T
= -int(-10*len(str(M
))//(3*L
))
5174 y
= _div_nearest(x
, T
)
5176 for i
in xrange(T
-1, 0, -1):
5177 y
= _div_nearest(x
*(Mshift
+ y
), Mshift
* i
)
5180 for k
in xrange(R
-1, -1, -1):
5181 Mshift
= long(M
)<<(k
+2)
5182 y
= _div_nearest(y
*(y
+Mshift
), Mshift
)
5187 """Compute an approximation to exp(c*10**e), with p decimal places of
5190 Returns integers d, f such that:
5192 10**(p-1) <= d <= 10**p, and
5193 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5195 In other words, d*10**f is an approximation to exp(c*10**e) with p
5196 digits of precision, and with an error in d of at most 1. This is
5197 almost, but not quite, the same as the error being < 1ulp: when d
5198 = 10**(p-1) the error could be up to 10 ulp."""
5200 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5203 # compute log(10) with extra precision = adjusted exponent of c*10**e
5204 extra
= max(0, e
+ len(str(c
)) - 1)
5207 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5211 cshift
= c
*10**shift
5213 cshift
= c
//10**-shift
5214 quot
, rem
= divmod(cshift
, _log10_digits(q
))
5216 # reduce remainder back to original precision
5217 rem
= _div_nearest(rem
, 10**extra
)
5219 # error in result of _iexp < 120; error after division < 0.62
5220 return _div_nearest(_iexp(rem
, 10**p
), 1000), quot
- p
+ 3
5222 def _dpower(xc
, xe
, yc
, ye
, p
):
5223 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5224 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5226 10**(p-1) <= c <= 10**p, and
5227 (c-1)*10**e < x**y < (c+1)*10**e
5229 in other words, c*10**e is an approximation to x**y with p digits
5230 of precision, and with an error in c of at most 1. (This is
5231 almost, but not quite, the same as the error being < 1ulp: when c
5232 == 10**(p-1) we can only guarantee error < 10ulp.)
5234 We assume that: x is positive and not equal to 1, and y is nonzero.
5237 # Find b such that 10**(b-1) <= |y| <= 10**b
5238 b
= len(str(abs(yc
))) + ye
5240 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5241 lxc
= _dlog(xc
, xe
, p
+b
+1)
5243 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5246 pc
= lxc
*yc
*10**shift
5248 pc
= _div_nearest(lxc
*yc
, 10**-shift
)
5251 # we prefer a result that isn't exactly 1; this makes it
5252 # easier to compute a correctly rounded result in __pow__
5253 if ((len(str(xc
)) + xe
>= 1) == (yc
> 0)): # if x**y > 1:
5254 coeff
, exp
= 10**(p
-1)+1, 1-p
5256 coeff
, exp
= 10**p
-1, -p
5258 coeff
, exp
= _dexp(pc
, -(p
+1), p
+1)
5259 coeff
= _div_nearest(coeff
, 10)
5264 def _log10_lb(c
, correction
= {
5265 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5266 '6': 23, '7': 16, '8': 10, '9': 5}):
5267 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5269 raise ValueError("The argument to _log10_lb should be nonnegative.")
5271 return 100*len(str_c
) - correction
[str_c
[0]]
5273 ##### Helper Functions ####################################################
5275 def _convert_other(other
, raiseit
=False):
5276 """Convert other to Decimal.
5278 Verifies that it's ok to use in an implicit construction.
5280 if isinstance(other
, Decimal
):
5282 if isinstance(other
, (int, long)):
5283 return Decimal(other
)
5285 raise TypeError("Unable to convert %s to Decimal" % other
)
5286 return NotImplemented
5288 ##### Setup Specific Contexts ############################################
5290 # The default context prototype used by Context()
5291 # Is mutable, so that new contexts can have different default values
5293 DefaultContext
= Context(
5294 prec
=28, rounding
=ROUND_HALF_EVEN
,
5295 traps
=[DivisionByZero
, Overflow
, InvalidOperation
],
5302 # Pre-made alternate contexts offered by the specification
5303 # Don't change these; the user should be able to select these
5304 # contexts and be able to reproduce results from other implementations
5307 BasicContext
= Context(
5308 prec
=9, rounding
=ROUND_HALF_UP
,
5309 traps
=[DivisionByZero
, Overflow
, InvalidOperation
, Clamped
, Underflow
],
5313 ExtendedContext
= Context(
5314 prec
=9, rounding
=ROUND_HALF_EVEN
,
5320 ##### crud for parsing strings #############################################
5322 # Regular expression used for parsing numeric strings. Additional
5325 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5326 # whitespace. But note that the specification disallows whitespace in
5329 # 2. For finite numbers (not infinities and NaNs) the body of the
5330 # number between the optional sign and the optional exponent must have
5331 # at least one decimal digit, possibly after the decimal point. The
5332 # lookahead expression '(?=\d|\.\d)' checks this.
5334 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5335 # other meaning for \d than the numbers [0-9].
5338 _parser
= re
.compile(r
""" # A numeric string consists of:
5340 (?P<sign>[-+])? # an optional sign, followed by either...
5342 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5343 (?P<int>[0-9]*) # having a (possibly empty) integer part
5344 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5345 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
5347 Inf(inity)? # ...an infinity, or...
5349 (?P<signal>s)? # ...an (optionally signaling)
5351 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
5355 """, re
.VERBOSE | re
.IGNORECASE
).match
5357 _all_zeros
= re
.compile('0*$').match
5358 _exact_half
= re
.compile('50*$').match
5360 ##### PEP3101 support functions ##############################################
5361 # The functions parse_format_specifier and format_align have little to do
5362 # with the Decimal class, and could potentially be reused for other pure
5363 # Python numeric classes that want to implement __format__
5365 # A format specifier for Decimal looks like:
5367 # [[fill]align][sign][0][minimumwidth][.precision][type]
5370 _parse_format_specifier_regex
= re
.compile(r
"""\A
5377 (?P<minimumwidth>(?!0)\d+)?
5378 (?:\.(?P<precision>0|(?!0)\d+))?
5379 (?P<type>[eEfFgG%])?
5385 def _parse_format_specifier(format_spec
):
5386 """Parse and validate a format specifier.
5388 Turns a standard numeric format specifier into a dict, with the
5391 fill: fill character to pad field to minimum width
5392 align: alignment type, either '<', '>', '=' or '^'
5393 sign: either '+', '-' or ' '
5394 minimumwidth: nonnegative integer giving minimum width
5395 precision: nonnegative integer giving precision, or None
5396 type: one of the characters 'eEfFgG%', or None
5397 unicode: either True or False (always True for Python 3.x)
5400 m
= _parse_format_specifier_regex
.match(format_spec
)
5402 raise ValueError("Invalid format specifier: " + format_spec
)
5404 # get the dictionary
5405 format_dict
= m
.groupdict()
5407 # defaults for fill and alignment
5408 fill
= format_dict
['fill']
5409 align
= format_dict
['align']
5410 if format_dict
.pop('zeropad') is not None:
5411 # in the face of conflict, refuse the temptation to guess
5412 if fill
is not None and fill
!= '0':
5413 raise ValueError("Fill character conflicts with '0'"
5414 " in format specifier: " + format_spec
)
5415 if align
is not None and align
!= '=':
5416 raise ValueError("Alignment conflicts with '0' in "
5417 "format specifier: " + format_spec
)
5420 format_dict
['fill'] = fill
or ' '
5421 format_dict
['align'] = align
or '<'
5423 if format_dict
['sign'] is None:
5424 format_dict
['sign'] = '-'
5426 # turn minimumwidth and precision entries into integers.
5427 # minimumwidth defaults to 0; precision remains None if not given
5428 format_dict
['minimumwidth'] = int(format_dict
['minimumwidth'] or '0')
5429 if format_dict
['precision'] is not None:
5430 format_dict
['precision'] = int(format_dict
['precision'])
5432 # if format type is 'g' or 'G' then a precision of 0 makes little
5433 # sense; convert it to 1. Same if format type is unspecified.
5434 if format_dict
['precision'] == 0:
5435 if format_dict
['type'] in 'gG' or format_dict
['type'] is None:
5436 format_dict
['precision'] = 1
5438 # record whether return type should be str or unicode
5439 format_dict
['unicode'] = isinstance(format_spec
, unicode)
5443 def _format_align(body
, spec_dict
):
5444 """Given an unpadded, non-aligned numeric string, add padding and
5445 aligment to conform with the given format specifier dictionary (as
5446 output from parse_format_specifier).
5448 It's assumed that if body is negative then it starts with '-'.
5449 Any leading sign ('-' or '+') is stripped from the body before
5450 applying the alignment and padding rules, and replaced in the
5451 appropriate position.
5454 # figure out the sign; we only examine the first character, so if
5455 # body has leading whitespace the results may be surprising.
5456 if len(body
) > 0 and body
[0] in '-+':
5463 if spec_dict
['sign'] in ' +':
5464 sign
= spec_dict
['sign']
5468 # how much extra space do we have to play with?
5469 minimumwidth
= spec_dict
['minimumwidth']
5470 fill
= spec_dict
['fill']
5471 padding
= fill
*(max(minimumwidth
- (len(sign
+body
)), 0))
5473 align
= spec_dict
['align']
5475 result
= padding
+ sign
+ body
5477 result
= sign
+ body
+ padding
5479 result
= sign
+ padding
+ body
5481 half
= len(padding
)//2
5482 result
= padding
[:half
] + sign
+ body
+ padding
[half
:]
5484 # make sure that result is unicode if necessary
5485 if spec_dict
['unicode']:
5486 result
= unicode(result
)
5490 ##### Useful Constants (internal use only) ################################
5493 Inf
= Decimal('Inf')
5494 negInf
= Decimal('-Inf')
5495 NaN
= Decimal('NaN')
5498 Dec_n1
= Decimal(-1)
5500 # Infsign[sign] is infinity w/ that sign
5501 Infsign
= (Inf
, negInf
)
5505 if __name__
== '__main__':
5507 doctest
.testmod(sys
.modules
[__name__
])