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
481 # The string below can't be included in the docstring until Python 2.6
482 # as the doctest module doesn't understand __future__ statements
484 >>> from __future__ import with_statement
485 >>> print getcontext().prec
487 >>> with localcontext():
488 ... ctx = getcontext()
493 >>> with localcontext(ExtendedContext):
494 ... print getcontext().prec
497 >>> print getcontext().prec
500 if ctx
is None: ctx
= getcontext()
501 return _ContextManager(ctx
)
504 ##### Decimal class #######################################################
506 class Decimal(object):
507 """Floating point class for decimal arithmetic."""
509 __slots__
= ('_exp','_int','_sign', '_is_special')
510 # Generally, the value of the Decimal instance is given by
511 # (-1)**_sign * _int * 10**_exp
512 # Special values are signified by _is_special == True
514 # We're immutable, so use __new__ not __init__
515 def __new__(cls
, value
="0", context
=None):
516 """Create a decimal point instance.
518 >>> Decimal('3.14') # string input
520 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
522 >>> Decimal(314) # int or long
524 >>> Decimal(Decimal(314)) # another decimal instance
526 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
530 # Note that the coefficient, self._int, is actually stored as
531 # a string rather than as a tuple of digits. This speeds up
532 # the "digits to integer" and "integer to digits" conversions
533 # that are used in almost every arithmetic operation on
534 # Decimals. This is an internal detail: the as_tuple function
535 # and the Decimal constructor still deal with tuples of
538 self
= object.__new
__(cls
)
541 # REs insist on real strings, so we can too.
542 if isinstance(value
, basestring
):
543 m
= _parser(value
.strip())
546 context
= getcontext()
547 return context
._raise
_error
(ConversionSyntax
,
548 "Invalid literal for Decimal: %r" % value
)
550 if m
.group('sign') == "-":
554 intpart
= m
.group('int')
555 if intpart
is not None:
557 fracpart
= m
.group('frac')
558 exp
= int(m
.group('exp') or '0')
559 if fracpart
is not None:
560 self
._int
= (intpart
+fracpart
).lstrip('0') or '0'
561 self
._exp
= exp
- len(fracpart
)
563 self
._int
= intpart
.lstrip('0') or '0'
565 self
._is
_special
= False
567 diag
= m
.group('diag')
570 self
._int
= diag
.lstrip('0')
571 if m
.group('signal'):
579 self
._is
_special
= True
583 if isinstance(value
, (int,long)):
589 self
._int
= str(abs(value
))
590 self
._is
_special
= False
593 # From another decimal
594 if isinstance(value
, Decimal
):
595 self
._exp
= value
._exp
596 self
._sign
= value
._sign
597 self
._int
= value
._int
598 self
._is
_special
= value
._is
_special
601 # From an internal working value
602 if isinstance(value
, _WorkRep
):
603 self
._sign
= value
.sign
604 self
._int
= str(value
.int)
605 self
._exp
= int(value
.exp
)
606 self
._is
_special
= False
609 # tuple/list conversion (possibly from as_tuple())
610 if isinstance(value
, (list,tuple)):
612 raise ValueError('Invalid tuple size in creation of Decimal '
613 'from list or tuple. The list or tuple '
614 'should have exactly three elements.')
615 # process sign. The isinstance test rejects floats
616 if not (isinstance(value
[0], (int, long)) and value
[0] in (0,1)):
617 raise ValueError("Invalid sign. The first value in the tuple "
618 "should be an integer; either 0 for a "
619 "positive number or 1 for a negative number.")
620 self
._sign
= value
[0]
622 # infinity: value[1] is ignored
625 self
._is
_special
= True
627 # process and validate the digits in value[1]
629 for digit
in value
[1]:
630 if isinstance(digit
, (int, long)) and 0 <= digit
<= 9:
632 if digits
or digit
!= 0:
635 raise ValueError("The second value in the tuple must "
636 "be composed of integers in the range "
638 if value
[2] in ('n', 'N'):
639 # NaN: digits form the diagnostic
640 self
._int
= ''.join(map(str, digits
))
642 self
._is
_special
= True
643 elif isinstance(value
[2], (int, long)):
644 # finite number: digits give the coefficient
645 self
._int
= ''.join(map(str, digits
or [0]))
647 self
._is
_special
= False
649 raise ValueError("The third value in the tuple must "
650 "be an integer, or one of the "
651 "strings 'F', 'n', 'N'.")
654 if isinstance(value
, float):
655 raise TypeError("Cannot convert float to Decimal. " +
656 "First convert the float to a string")
658 raise TypeError("Cannot convert %r to Decimal" % value
)
661 """Returns whether the number is not actually one.
675 def _isinfinity(self
):
676 """Returns whether the number is infinite
678 0 if finite or not a number
688 def _check_nans(self
, other
=None, context
=None):
689 """Returns whether the number is not actually one.
691 if self, other are sNaN, signal
692 if self, other are NaN return nan
695 Done before operations.
698 self_is_nan
= self
._isnan
()
702 other_is_nan
= other
._isnan
()
704 if self_is_nan
or other_is_nan
:
706 context
= getcontext()
709 return context
._raise
_error
(InvalidOperation
, 'sNaN',
711 if other_is_nan
== 2:
712 return context
._raise
_error
(InvalidOperation
, 'sNaN',
715 return self
._fix
_nan
(context
)
717 return other
._fix
_nan
(context
)
720 def __nonzero__(self
):
721 """Return True if self is nonzero; otherwise return False.
723 NaNs and infinities are considered nonzero.
725 return self
._is
_special
or self
._int
!= '0'
727 def __cmp__(self
, other
):
728 other
= _convert_other(other
)
729 if other
is NotImplemented:
730 # Never return NotImplemented
733 if self
._is
_special
or other
._is
_special
:
734 # check for nans, without raising on a signaling nan
735 if self
._isnan
() or other
._isnan
():
736 return 1 # Comparison involving NaN's always reports self > other
739 return cmp(self
._isinfinity
(), other
._isinfinity
())
741 # check for zeros; note that cmp(0, -0) should return 0
746 return -((-1)**other
._sign
)
748 return (-1)**self
._sign
750 # If different signs, neg one is less
751 if other
._sign
< self
._sign
:
753 if self
._sign
< other
._sign
:
756 self_adjusted
= self
.adjusted()
757 other_adjusted
= other
.adjusted()
758 if self_adjusted
== other_adjusted
:
759 self_padded
= self
._int
+ '0'*(self
._exp
- other
._exp
)
760 other_padded
= other
._int
+ '0'*(other
._exp
- self
._exp
)
761 return cmp(self_padded
, other_padded
) * (-1)**self
._sign
762 elif self_adjusted
> other_adjusted
:
763 return (-1)**self
._sign
764 else: # self_adjusted < other_adjusted
765 return -((-1)**self
._sign
)
767 def __eq__(self
, other
):
768 if not isinstance(other
, (Decimal
, int, long)):
769 return NotImplemented
770 return self
.__cmp
__(other
) == 0
772 def __ne__(self
, other
):
773 if not isinstance(other
, (Decimal
, int, long)):
774 return NotImplemented
775 return self
.__cmp
__(other
) != 0
777 def compare(self
, other
, context
=None):
778 """Compares one to another.
784 Like __cmp__, but returns Decimal instances.
786 other
= _convert_other(other
, raiseit
=True)
788 # Compare(NaN, NaN) = NaN
789 if (self
._is
_special
or other
and other
._is
_special
):
790 ans
= self
._check
_nans
(other
, context
)
794 return Decimal(self
.__cmp
__(other
))
797 """x.__hash__() <==> hash(x)"""
798 # Decimal integers must hash the same as the ints
800 # The hash of a nonspecial noninteger Decimal must depend only
801 # on the value of that Decimal, and not on its representation.
802 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
805 raise TypeError('Cannot hash a NaN value.')
806 return hash(str(self
))
809 if self
._isinteger
():
810 op
= _WorkRep(self
.to_integral_value())
811 # to make computation feasible for Decimals with large
812 # exponent, we use the fact that hash(n) == hash(m) for
813 # any two nonzero integers n and m such that (i) n and m
814 # have the same sign, and (ii) n is congruent to m modulo
815 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
816 # hash((-1)**s*c*pow(10, e, 2**64-1).
817 return hash((-1)**op
.sign
*op
.int*pow(10, op
.exp
, 2**64-1))
818 # The value of a nonzero nonspecial Decimal instance is
819 # faithfully represented by the triple consisting of its sign,
820 # its adjusted exponent, and its coefficient with trailing
822 return hash((self
._sign
,
823 self
._exp
+len(self
._int
),
824 self
._int
.rstrip('0')))
827 """Represents the number as a triple tuple.
829 To show the internals exactly as they are.
831 return DecimalTuple(self
._sign
, tuple(map(int, self
._int
)), self
._exp
)
834 """Represents the number as an instance of Decimal."""
835 # Invariant: eval(repr(d)) == d
836 return 'Decimal("%s")' % str(self
)
838 def __str__(self
, eng
=False, context
=None):
839 """Return string representation of the number in scientific notation.
841 Captures all of the information in the underlying representation.
844 sign
= ['', '-'][self
._sign
]
847 return sign
+ 'Infinity'
848 elif self
._exp
== 'n':
849 return sign
+ 'NaN' + self
._int
850 else: # self._exp == 'N'
851 return sign
+ 'sNaN' + self
._int
853 # number of digits of self._int to left of decimal point
854 leftdigits
= self
._exp
+ len(self
._int
)
856 # dotplace is number of digits of self._int to the left of the
857 # decimal point in the mantissa of the output string (that is,
858 # after adjusting the exponent)
859 if self
._exp
<= 0 and leftdigits
> -6:
860 # no exponent required
861 dotplace
= leftdigits
863 # usual scientific notation: 1 digit on left of the point
865 elif self
._int
== '0':
866 # engineering notation, zero
867 dotplace
= (leftdigits
+ 1) % 3 - 1
869 # engineering notation, nonzero
870 dotplace
= (leftdigits
- 1) % 3 + 1
874 fracpart
= '.' + '0'*(-dotplace
) + self
._int
875 elif dotplace
>= len(self
._int
):
876 intpart
= self
._int
+'0'*(dotplace
-len(self
._int
))
879 intpart
= self
._int
[:dotplace
]
880 fracpart
= '.' + self
._int
[dotplace
:]
881 if leftdigits
== dotplace
:
885 context
= getcontext()
886 exp
= ['e', 'E'][context
.capitals
] + "%+d" % (leftdigits
-dotplace
)
888 return sign
+ intpart
+ fracpart
+ exp
890 def to_eng_string(self
, context
=None):
891 """Convert to engineering-type string.
893 Engineering notation has an exponent which is a multiple of 3, so there
894 are up to 3 digits left of the decimal place.
896 Same rules for when in exponential and when as a value as in __str__.
898 return self
.__str
__(eng
=True, context
=context
)
900 def __neg__(self
, context
=None):
901 """Returns a copy with the sign switched.
903 Rounds, if it has reason.
906 ans
= self
._check
_nans
(context
=context
)
911 # -Decimal('0') is Decimal('0'), not Decimal('-0')
912 ans
= self
.copy_abs()
914 ans
= self
.copy_negate()
917 context
= getcontext()
918 return ans
._fix
(context
)
920 def __pos__(self
, context
=None):
921 """Returns a copy, unless it is a sNaN.
923 Rounds the number (if more then precision digits)
926 ans
= self
._check
_nans
(context
=context
)
932 ans
= self
.copy_abs()
937 context
= getcontext()
938 return ans
._fix
(context
)
940 def __abs__(self
, round=True, context
=None):
941 """Returns the absolute value of self.
943 If the keyword argument 'round' is false, do not round. The
944 expression self.__abs__(round=False) is equivalent to
948 return self
.copy_abs()
951 ans
= self
._check
_nans
(context
=context
)
956 ans
= self
.__neg
__(context
=context
)
958 ans
= self
.__pos
__(context
=context
)
962 def __add__(self
, other
, context
=None):
963 """Returns self + other.
965 -INF + INF (or the reverse) cause InvalidOperation errors.
967 other
= _convert_other(other
)
968 if other
is NotImplemented:
972 context
= getcontext()
974 if self
._is
_special
or other
._is
_special
:
975 ans
= self
._check
_nans
(other
, context
)
979 if self
._isinfinity
():
980 # If both INF, same sign => same as both, opposite => error.
981 if self
._sign
!= other
._sign
and other
._isinfinity
():
982 return context
._raise
_error
(InvalidOperation
, '-INF + INF')
984 if other
._isinfinity
():
985 return Decimal(other
) # Can't both be infinity here
987 exp
= min(self
._exp
, other
._exp
)
989 if context
.rounding
== ROUND_FLOOR
and self
._sign
!= other
._sign
:
990 # If the answer is 0, the sign should be negative, in this case.
993 if not self
and not other
:
994 sign
= min(self
._sign
, other
._sign
)
997 ans
= _dec_from_triple(sign
, '0', exp
)
998 ans
= ans
._fix
(context
)
1001 exp
= max(exp
, other
._exp
- context
.prec
-1)
1002 ans
= other
._rescale
(exp
, context
.rounding
)
1003 ans
= ans
._fix
(context
)
1006 exp
= max(exp
, self
._exp
- context
.prec
-1)
1007 ans
= self
._rescale
(exp
, context
.rounding
)
1008 ans
= ans
._fix
(context
)
1011 op1
= _WorkRep(self
)
1012 op2
= _WorkRep(other
)
1013 op1
, op2
= _normalize(op1
, op2
, context
.prec
)
1016 if op1
.sign
!= op2
.sign
:
1017 # Equal and opposite
1018 if op1
.int == op2
.int:
1019 ans
= _dec_from_triple(negativezero
, '0', exp
)
1020 ans
= ans
._fix
(context
)
1022 if op1
.int < op2
.int:
1024 # OK, now abs(op1) > abs(op2)
1027 op1
.sign
, op2
.sign
= op2
.sign
, op1
.sign
1030 # So we know the sign, and op1 > 0.
1033 op1
.sign
, op2
.sign
= (0, 0)
1036 # Now, op1 > abs(op2) > 0
1039 result
.int = op1
.int + op2
.int
1041 result
.int = op1
.int - op2
.int
1043 result
.exp
= op1
.exp
1044 ans
= Decimal(result
)
1045 ans
= ans
._fix
(context
)
1050 def __sub__(self
, other
, context
=None):
1051 """Return self - other"""
1052 other
= _convert_other(other
)
1053 if other
is NotImplemented:
1056 if self
._is
_special
or other
._is
_special
:
1057 ans
= self
._check
_nans
(other
, context
=context
)
1061 # self - other is computed as self + other.copy_negate()
1062 return self
.__add
__(other
.copy_negate(), context
=context
)
1064 def __rsub__(self
, other
, context
=None):
1065 """Return other - self"""
1066 other
= _convert_other(other
)
1067 if other
is NotImplemented:
1070 return other
.__sub
__(self
, context
=context
)
1072 def __mul__(self
, other
, context
=None):
1073 """Return self * other.
1075 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1077 other
= _convert_other(other
)
1078 if other
is NotImplemented:
1082 context
= getcontext()
1084 resultsign
= self
._sign ^ other
._sign
1086 if self
._is
_special
or other
._is
_special
:
1087 ans
= self
._check
_nans
(other
, context
)
1091 if self
._isinfinity
():
1093 return context
._raise
_error
(InvalidOperation
, '(+-)INF * 0')
1094 return Infsign
[resultsign
]
1096 if other
._isinfinity
():
1098 return context
._raise
_error
(InvalidOperation
, '0 * (+-)INF')
1099 return Infsign
[resultsign
]
1101 resultexp
= self
._exp
+ other
._exp
1103 # Special case for multiplying by zero
1104 if not self
or not other
:
1105 ans
= _dec_from_triple(resultsign
, '0', resultexp
)
1106 # Fixing in case the exponent is out of bounds
1107 ans
= ans
._fix
(context
)
1110 # Special case for multiplying by power of 10
1111 if self
._int
== '1':
1112 ans
= _dec_from_triple(resultsign
, other
._int
, resultexp
)
1113 ans
= ans
._fix
(context
)
1115 if other
._int
== '1':
1116 ans
= _dec_from_triple(resultsign
, self
._int
, resultexp
)
1117 ans
= ans
._fix
(context
)
1120 op1
= _WorkRep(self
)
1121 op2
= _WorkRep(other
)
1123 ans
= _dec_from_triple(resultsign
, str(op1
.int * op2
.int), resultexp
)
1124 ans
= ans
._fix
(context
)
1129 def __div__(self
, other
, context
=None):
1130 """Return self / other."""
1131 other
= _convert_other(other
)
1132 if other
is NotImplemented:
1133 return NotImplemented
1136 context
= getcontext()
1138 sign
= self
._sign ^ other
._sign
1140 if self
._is
_special
or other
._is
_special
:
1141 ans
= self
._check
_nans
(other
, context
)
1145 if self
._isinfinity
() and other
._isinfinity
():
1146 return context
._raise
_error
(InvalidOperation
, '(+-)INF/(+-)INF')
1148 if self
._isinfinity
():
1149 return Infsign
[sign
]
1151 if other
._isinfinity
():
1152 context
._raise
_error
(Clamped
, 'Division by infinity')
1153 return _dec_from_triple(sign
, '0', context
.Etiny())
1155 # Special cases for zeroes
1158 return context
._raise
_error
(DivisionUndefined
, '0 / 0')
1159 return context
._raise
_error
(DivisionByZero
, 'x / 0', sign
)
1162 exp
= self
._exp
- other
._exp
1165 # OK, so neither = 0, INF or NaN
1166 shift
= len(other
._int
) - len(self
._int
) + context
.prec
+ 1
1167 exp
= self
._exp
- other
._exp
- shift
1168 op1
= _WorkRep(self
)
1169 op2
= _WorkRep(other
)
1171 coeff
, remainder
= divmod(op1
.int * 10**shift
, op2
.int)
1173 coeff
, remainder
= divmod(op1
.int, op2
.int * 10**-shift
)
1175 # result is not exact; adjust to ensure correct rounding
1179 # result is exact; get as close to ideal exponent as possible
1180 ideal_exp
= self
._exp
- other
._exp
1181 while exp
< ideal_exp
and coeff
% 10 == 0:
1185 ans
= _dec_from_triple(sign
, str(coeff
), exp
)
1186 return ans
._fix
(context
)
1188 __truediv__
= __div__
1190 def _divide(self
, other
, context
):
1191 """Return (self // other, self % other), to context.prec precision.
1193 Assumes that neither self nor other is a NaN, that self is not
1194 infinite and that other is nonzero.
1196 sign
= self
._sign ^ other
._sign
1197 if other
._isinfinity
():
1198 ideal_exp
= self
._exp
1200 ideal_exp
= min(self
._exp
, other
._exp
)
1202 expdiff
= self
.adjusted() - other
.adjusted()
1203 if not self
or other
._isinfinity
() or expdiff
<= -2:
1204 return (_dec_from_triple(sign
, '0', 0),
1205 self
._rescale
(ideal_exp
, context
.rounding
))
1206 if expdiff
<= context
.prec
:
1207 op1
= _WorkRep(self
)
1208 op2
= _WorkRep(other
)
1209 if op1
.exp
>= op2
.exp
:
1210 op1
.int *= 10**(op1
.exp
- op2
.exp
)
1212 op2
.int *= 10**(op2
.exp
- op1
.exp
)
1213 q
, r
= divmod(op1
.int, op2
.int)
1214 if q
< 10**context
.prec
:
1215 return (_dec_from_triple(sign
, str(q
), 0),
1216 _dec_from_triple(self
._sign
, str(r
), ideal_exp
))
1218 # Here the quotient is too large to be representable
1219 ans
= context
._raise
_error
(DivisionImpossible
,
1220 'quotient too large in //, % or divmod')
1223 def __rdiv__(self
, other
, context
=None):
1224 """Swaps self/other and returns __div__."""
1225 other
= _convert_other(other
)
1226 if other
is NotImplemented:
1228 return other
.__div
__(self
, context
=context
)
1229 __rtruediv__
= __rdiv__
1231 def __divmod__(self
, other
, context
=None):
1233 Return (self // other, self % other)
1235 other
= _convert_other(other
)
1236 if other
is NotImplemented:
1240 context
= getcontext()
1242 ans
= self
._check
_nans
(other
, context
)
1246 sign
= self
._sign ^ other
._sign
1247 if self
._isinfinity
():
1248 if other
._isinfinity
():
1249 ans
= context
._raise
_error
(InvalidOperation
, 'divmod(INF, INF)')
1252 return (Infsign
[sign
],
1253 context
._raise
_error
(InvalidOperation
, 'INF % x'))
1257 ans
= context
._raise
_error
(DivisionUndefined
, 'divmod(0, 0)')
1260 return (context
._raise
_error
(DivisionByZero
, 'x // 0', sign
),
1261 context
._raise
_error
(InvalidOperation
, 'x % 0'))
1263 quotient
, remainder
= self
._divide
(other
, context
)
1264 remainder
= remainder
._fix
(context
)
1265 return quotient
, remainder
1267 def __rdivmod__(self
, other
, context
=None):
1268 """Swaps self/other and returns __divmod__."""
1269 other
= _convert_other(other
)
1270 if other
is NotImplemented:
1272 return other
.__divmod
__(self
, context
=context
)
1274 def __mod__(self
, other
, context
=None):
1278 other
= _convert_other(other
)
1279 if other
is NotImplemented:
1283 context
= getcontext()
1285 ans
= self
._check
_nans
(other
, context
)
1289 if self
._isinfinity
():
1290 return context
._raise
_error
(InvalidOperation
, 'INF % x')
1293 return context
._raise
_error
(InvalidOperation
, 'x % 0')
1295 return context
._raise
_error
(DivisionUndefined
, '0 % 0')
1297 remainder
= self
._divide
(other
, context
)[1]
1298 remainder
= remainder
._fix
(context
)
1301 def __rmod__(self
, other
, context
=None):
1302 """Swaps self/other and returns __mod__."""
1303 other
= _convert_other(other
)
1304 if other
is NotImplemented:
1306 return other
.__mod
__(self
, context
=context
)
1308 def remainder_near(self
, other
, context
=None):
1310 Remainder nearest to 0- abs(remainder-near) <= other/2
1313 context
= getcontext()
1315 other
= _convert_other(other
, raiseit
=True)
1317 ans
= self
._check
_nans
(other
, context
)
1321 # self == +/-infinity -> InvalidOperation
1322 if self
._isinfinity
():
1323 return context
._raise
_error
(InvalidOperation
,
1324 'remainder_near(infinity, x)')
1326 # other == 0 -> either InvalidOperation or DivisionUndefined
1329 return context
._raise
_error
(InvalidOperation
,
1330 'remainder_near(x, 0)')
1332 return context
._raise
_error
(DivisionUndefined
,
1333 'remainder_near(0, 0)')
1335 # other = +/-infinity -> remainder = self
1336 if other
._isinfinity
():
1338 return ans
._fix
(context
)
1340 # self = 0 -> remainder = self, with ideal exponent
1341 ideal_exponent
= min(self
._exp
, other
._exp
)
1343 ans
= _dec_from_triple(self
._sign
, '0', ideal_exponent
)
1344 return ans
._fix
(context
)
1346 # catch most cases of large or small quotient
1347 expdiff
= self
.adjusted() - other
.adjusted()
1348 if expdiff
>= context
.prec
+ 1:
1349 # expdiff >= prec+1 => abs(self/other) > 10**prec
1350 return context
._raise
_error
(DivisionImpossible
)
1352 # expdiff <= -2 => abs(self/other) < 0.1
1353 ans
= self
._rescale
(ideal_exponent
, context
.rounding
)
1354 return ans
._fix
(context
)
1356 # adjust both arguments to have the same exponent, then divide
1357 op1
= _WorkRep(self
)
1358 op2
= _WorkRep(other
)
1359 if op1
.exp
>= op2
.exp
:
1360 op1
.int *= 10**(op1
.exp
- op2
.exp
)
1362 op2
.int *= 10**(op2
.exp
- op1
.exp
)
1363 q
, r
= divmod(op1
.int, op2
.int)
1364 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1365 # 10**ideal_exponent. Apply correction to ensure that
1366 # abs(remainder) <= abs(other)/2
1367 if 2*r
+ (q
&1) > op2
.int:
1371 if q
>= 10**context
.prec
:
1372 return context
._raise
_error
(DivisionImpossible
)
1374 # result has same sign as self unless r is negative
1380 ans
= _dec_from_triple(sign
, str(r
), ideal_exponent
)
1381 return ans
._fix
(context
)
1383 def __floordiv__(self
, other
, context
=None):
1385 other
= _convert_other(other
)
1386 if other
is NotImplemented:
1390 context
= getcontext()
1392 ans
= self
._check
_nans
(other
, context
)
1396 if self
._isinfinity
():
1397 if other
._isinfinity
():
1398 return context
._raise
_error
(InvalidOperation
, 'INF // INF')
1400 return Infsign
[self
._sign ^ other
._sign
]
1404 return context
._raise
_error
(DivisionByZero
, 'x // 0',
1405 self
._sign ^ other
._sign
)
1407 return context
._raise
_error
(DivisionUndefined
, '0 // 0')
1409 return self
._divide
(other
, context
)[0]
1411 def __rfloordiv__(self
, other
, context
=None):
1412 """Swaps self/other and returns __floordiv__."""
1413 other
= _convert_other(other
)
1414 if other
is NotImplemented:
1416 return other
.__floordiv
__(self
, context
=context
)
1418 def __float__(self
):
1419 """Float representation."""
1420 return float(str(self
))
1423 """Converts self to an int, truncating if necessary."""
1424 if self
._is
_special
:
1426 context
= getcontext()
1427 return context
._raise
_error
(InvalidContext
)
1428 elif self
._isinfinity
():
1429 raise OverflowError("Cannot convert infinity to long")
1430 s
= (-1)**self
._sign
1432 return s
*int(self
._int
)*10**self
._exp
1434 return s
*int(self
._int
[:self
._exp
] or '0')
1437 """Converts to a long.
1439 Equivalent to long(int(self))
1441 return long(self
.__int
__())
1443 def _fix_nan(self
, context
):
1444 """Decapitate the payload of a NaN to fit the context"""
1447 # maximum length of payload is precision if _clamp=0,
1448 # precision-1 if _clamp=1.
1449 max_payload_len
= context
.prec
- context
._clamp
1450 if len(payload
) > max_payload_len
:
1451 payload
= payload
[len(payload
)-max_payload_len
:].lstrip('0')
1452 return _dec_from_triple(self
._sign
, payload
, self
._exp
, True)
1453 return Decimal(self
)
1455 def _fix(self
, context
):
1456 """Round if it is necessary to keep self within prec precision.
1458 Rounds and fixes the exponent. Does not raise on a sNaN.
1461 self - Decimal instance
1462 context - context used.
1465 if self
._is
_special
:
1467 # decapitate payload if necessary
1468 return self
._fix
_nan
(context
)
1470 # self is +/-Infinity; return unaltered
1471 return Decimal(self
)
1473 # if self is zero then exponent should be between Etiny and
1474 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1475 Etiny
= context
.Etiny()
1476 Etop
= context
.Etop()
1478 exp_max
= [context
.Emax
, Etop
][context
._clamp
]
1479 new_exp
= min(max(self
._exp
, Etiny
), exp_max
)
1480 if new_exp
!= self
._exp
:
1481 context
._raise
_error
(Clamped
)
1482 return _dec_from_triple(self
._sign
, '0', new_exp
)
1484 return Decimal(self
)
1486 # exp_min is the smallest allowable exponent of the result,
1487 # equal to max(self.adjusted()-context.prec+1, Etiny)
1488 exp_min
= len(self
._int
) + self
._exp
- context
.prec
1490 # overflow: exp_min > Etop iff self.adjusted() > Emax
1491 context
._raise
_error
(Inexact
)
1492 context
._raise
_error
(Rounded
)
1493 return context
._raise
_error
(Overflow
, 'above Emax', self
._sign
)
1494 self_is_subnormal
= exp_min
< Etiny
1495 if self_is_subnormal
:
1496 context
._raise
_error
(Subnormal
)
1499 # round if self has too many digits
1500 if self
._exp
< exp_min
:
1501 context
._raise
_error
(Rounded
)
1502 digits
= len(self
._int
) + self
._exp
- exp_min
1504 self
= _dec_from_triple(self
._sign
, '1', exp_min
-1)
1506 this_function
= getattr(self
, self
._pick
_rounding
_function
[context
.rounding
])
1507 changed
= this_function(digits
)
1508 coeff
= self
._int
[:digits
] or '0'
1510 coeff
= str(int(coeff
)+1)
1511 ans
= _dec_from_triple(self
._sign
, coeff
, exp_min
)
1514 context
._raise
_error
(Inexact
)
1515 if self_is_subnormal
:
1516 context
._raise
_error
(Underflow
)
1518 # raise Clamped on underflow to 0
1519 context
._raise
_error
(Clamped
)
1520 elif len(ans
._int
) == context
.prec
+1:
1521 # we get here only if rescaling rounds the
1522 # cofficient up to exactly 10**context.prec
1524 ans
= _dec_from_triple(ans
._sign
,
1525 ans
._int
[:-1], ans
._exp
+1)
1527 # Inexact and Rounded have already been raised
1528 ans
= context
._raise
_error
(Overflow
, 'above Emax',
1532 # fold down if _clamp == 1 and self has too few digits
1533 if context
._clamp
== 1 and self
._exp
> Etop
:
1534 context
._raise
_error
(Clamped
)
1535 self_padded
= self
._int
+ '0'*(self
._exp
- Etop
)
1536 return _dec_from_triple(self
._sign
, self_padded
, Etop
)
1538 # here self was representable to begin with; return unchanged
1539 return Decimal(self
)
1541 _pick_rounding_function
= {}
1543 # for each of the rounding functions below:
1544 # self is a finite, nonzero Decimal
1545 # prec is an integer satisfying 0 <= prec < len(self._int)
1547 # each function returns either -1, 0, or 1, as follows:
1548 # 1 indicates that self should be rounded up (away from zero)
1549 # 0 indicates that self should be truncated, and that all the
1550 # digits to be truncated are zeros (so the value is unchanged)
1551 # -1 indicates that there are nonzero digits to be truncated
1553 def _round_down(self
, prec
):
1554 """Also known as round-towards-0, truncate."""
1555 if _all_zeros(self
._int
, prec
):
1560 def _round_up(self
, prec
):
1561 """Rounds away from 0."""
1562 return -self
._round
_down
(prec
)
1564 def _round_half_up(self
, prec
):
1565 """Rounds 5 up (away from 0)"""
1566 if self
._int
[prec
] in '56789':
1568 elif _all_zeros(self
._int
, prec
):
1573 def _round_half_down(self
, prec
):
1575 if _exact_half(self
._int
, prec
):
1578 return self
._round
_half
_up
(prec
)
1580 def _round_half_even(self
, prec
):
1581 """Round 5 to even, rest to nearest."""
1582 if _exact_half(self
._int
, prec
) and \
1583 (prec
== 0 or self
._int
[prec
-1] in '02468'):
1586 return self
._round
_half
_up
(prec
)
1588 def _round_ceiling(self
, prec
):
1589 """Rounds up (not away from 0 if negative.)"""
1591 return self
._round
_down
(prec
)
1593 return -self
._round
_down
(prec
)
1595 def _round_floor(self
, prec
):
1596 """Rounds down (not towards 0 if negative)"""
1598 return self
._round
_down
(prec
)
1600 return -self
._round
_down
(prec
)
1602 def _round_05up(self
, prec
):
1603 """Round down unless digit prec-1 is 0 or 5."""
1604 if prec
and self
._int
[prec
-1] not in '05':
1605 return self
._round
_down
(prec
)
1607 return -self
._round
_down
(prec
)
1609 def fma(self
, other
, third
, context
=None):
1610 """Fused multiply-add.
1612 Returns self*other+third with no rounding of the intermediate
1615 self and other are multiplied together, with no rounding of
1616 the result. The third operand is then added to the result,
1617 and a single final rounding is performed.
1620 other
= _convert_other(other
, raiseit
=True)
1622 # compute product; raise InvalidOperation if either operand is
1623 # a signaling NaN or if the product is zero times infinity.
1624 if self
._is
_special
or other
._is
_special
:
1626 context
= getcontext()
1627 if self
._exp
== 'N':
1628 return context
._raise
_error
(InvalidOperation
, 'sNaN', self
)
1629 if other
._exp
== 'N':
1630 return context
._raise
_error
(InvalidOperation
, 'sNaN', other
)
1631 if self
._exp
== 'n':
1633 elif other
._exp
== 'n':
1635 elif self
._exp
== 'F':
1637 return context
._raise
_error
(InvalidOperation
,
1639 product
= Infsign
[self
._sign ^ other
._sign
]
1640 elif other
._exp
== 'F':
1642 return context
._raise
_error
(InvalidOperation
,
1644 product
= Infsign
[self
._sign ^ other
._sign
]
1646 product
= _dec_from_triple(self
._sign ^ other
._sign
,
1647 str(int(self
._int
) * int(other
._int
)),
1648 self
._exp
+ other
._exp
)
1650 third
= _convert_other(third
, raiseit
=True)
1651 return product
.__add
__(third
, context
)
1653 def _power_modulo(self
, other
, modulo
, context
=None):
1654 """Three argument version of __pow__"""
1656 # if can't convert other and modulo to Decimal, raise
1657 # TypeError; there's no point returning NotImplemented (no
1658 # equivalent of __rpow__ for three argument pow)
1659 other
= _convert_other(other
, raiseit
=True)
1660 modulo
= _convert_other(modulo
, raiseit
=True)
1663 context
= getcontext()
1665 # deal with NaNs: if there are any sNaNs then first one wins,
1666 # (i.e. behaviour for NaNs is identical to that of fma)
1667 self_is_nan
= self
._isnan
()
1668 other_is_nan
= other
._isnan
()
1669 modulo_is_nan
= modulo
._isnan
()
1670 if self_is_nan
or other_is_nan
or modulo_is_nan
:
1671 if self_is_nan
== 2:
1672 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1674 if other_is_nan
== 2:
1675 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1677 if modulo_is_nan
== 2:
1678 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1681 return self
._fix
_nan
(context
)
1683 return other
._fix
_nan
(context
)
1684 return modulo
._fix
_nan
(context
)
1686 # check inputs: we apply same restrictions as Python's pow()
1687 if not (self
._isinteger
() and
1688 other
._isinteger
() and
1689 modulo
._isinteger
()):
1690 return context
._raise
_error
(InvalidOperation
,
1691 'pow() 3rd argument not allowed '
1692 'unless all arguments are integers')
1694 return context
._raise
_error
(InvalidOperation
,
1695 'pow() 2nd argument cannot be '
1696 'negative when 3rd argument specified')
1698 return context
._raise
_error
(InvalidOperation
,
1699 'pow() 3rd argument cannot be 0')
1701 # additional restriction for decimal: the modulus must be less
1702 # than 10**prec in absolute value
1703 if modulo
.adjusted() >= context
.prec
:
1704 return context
._raise
_error
(InvalidOperation
,
1705 'insufficient precision: pow() 3rd '
1706 'argument must not have more than '
1709 # define 0**0 == NaN, for consistency with two-argument pow
1710 # (even though it hurts!)
1711 if not other
and not self
:
1712 return context
._raise
_error
(InvalidOperation
,
1713 'at least one of pow() 1st argument '
1714 'and 2nd argument must be nonzero ;'
1715 '0**0 is not defined')
1717 # compute sign of result
1723 # convert modulo to a Python integer, and self and other to
1724 # Decimal integers (i.e. force their exponents to be >= 0)
1725 modulo
= abs(int(modulo
))
1726 base
= _WorkRep(self
.to_integral_value())
1727 exponent
= _WorkRep(other
.to_integral_value())
1729 # compute result using integer pow()
1730 base
= (base
.int % modulo
* pow(10, base
.exp
, modulo
)) % modulo
1731 for i
in xrange(exponent
.exp
):
1732 base
= pow(base
, 10, modulo
)
1733 base
= pow(base
, exponent
.int, modulo
)
1735 return _dec_from_triple(sign
, str(base
), 0)
1737 def _power_exact(self
, other
, p
):
1738 """Attempt to compute self**other exactly.
1740 Given Decimals self and other and an integer p, attempt to
1741 compute an exact result for the power self**other, with p
1742 digits of precision. Return None if self**other is not
1743 exactly representable in p digits.
1745 Assumes that elimination of special cases has already been
1746 performed: self and other must both be nonspecial; self must
1747 be positive and not numerically equal to 1; other must be
1748 nonzero. For efficiency, other._exp should not be too large,
1749 so that 10**abs(other._exp) is a feasible calculation."""
1751 # In the comments below, we write x for the value of self and
1752 # y for the value of other. Write x = xc*10**xe and y =
1755 # The main purpose of this method is to identify the *failure*
1756 # of x**y to be exactly representable with as little effort as
1757 # possible. So we look for cheap and easy tests that
1758 # eliminate the possibility of x**y being exact. Only if all
1759 # these tests are passed do we go on to actually compute x**y.
1761 # Here's the main idea. First normalize both x and y. We
1762 # express y as a rational m/n, with m and n relatively prime
1763 # and n>0. Then for x**y to be exactly representable (at
1764 # *any* precision), xc must be the nth power of a positive
1765 # integer and xe must be divisible by n. If m is negative
1766 # then additionally xc must be a power of either 2 or 5, hence
1767 # a power of 2**n or 5**n.
1769 # There's a limit to how small |y| can be: if y=m/n as above
1772 # (1) if xc != 1 then for the result to be representable we
1773 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1774 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1775 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1778 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1779 # |y| < 1/|xe| then the result is not representable.
1781 # Note that since x is not equal to 1, at least one of (1) and
1782 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1783 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1785 # There's also a limit to how large y can be, at least if it's
1786 # positive: the normalized result will have coefficient xc**y,
1787 # so if it's representable then xc**y < 10**p, and y <
1788 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1789 # not exactly representable.
1791 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1792 # so |y| < 1/xe and the result is not representable.
1793 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1797 xc
, xe
= x
.int, x
.exp
1803 yc
, ye
= y
.int, y
.exp
1808 # case where xc == 1: result is 10**(xe*y), with xe*y
1809 # required to be an integer
1812 exponent
= xe
*yc
*10**ye
1814 exponent
, remainder
= divmod(xe
*yc
, 10**-ye
)
1818 exponent
= -exponent
1819 # if other is a nonnegative integer, use ideal exponent
1820 if other
._isinteger
() and other
._sign
== 0:
1821 ideal_exponent
= self
._exp
*int(other
)
1822 zeros
= min(exponent
-ideal_exponent
, p
-1)
1825 return _dec_from_triple(0, '1' + '0'*zeros
, exponent
-zeros
)
1827 # case where y is negative: xc must be either a power
1828 # of 2 or a power of 5.
1830 last_digit
= xc
% 10
1831 if last_digit
in (2,4,6,8):
1832 # quick test for power of 2
1835 # now xc is a power of 2; e is its exponent
1837 # find e*y and xe*y; both must be integers
1839 y_as_int
= yc
*10**ye
1844 e
, remainder
= divmod(e
*yc
, ten_pow
)
1847 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1851 if e
*65 >= p
*93: # 93/65 > log(10)/log(5)
1855 elif last_digit
== 5:
1856 # e >= log_5(xc) if xc is a power of 5; we have
1857 # equality all the way up to xc=5**2658
1858 e
= _nbits(xc
)*28//65
1859 xc
, remainder
= divmod(5**e
, xc
)
1866 y_as_integer
= yc
*10**ye
1868 xe
= xe
*y_as_integer
1871 e
, remainder
= divmod(e
*yc
, ten_pow
)
1874 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
1877 if e
*3 >= p
*10: # 10/3 > log(10)/log(2)
1886 return _dec_from_triple(0, str(xc
), xe
)
1888 # now y is positive; find m and n such that y = m/n
1892 if xe
!= 0 and len(str(abs(yc
*xe
))) <= -ye
:
1894 xc_bits
= _nbits(xc
)
1895 if xc
!= 1 and len(str(abs(yc
)*xc_bits
)) <= -ye
:
1897 m
, n
= yc
, 10**(-ye
)
1898 while m
% 2 == n
% 2 == 0:
1901 while m
% 5 == n
% 5 == 0:
1905 # compute nth root of xc*10**xe
1907 # if 1 < xc < 2**n then xc isn't an nth power
1908 if xc
!= 1 and xc_bits
<= n
:
1911 xe
, rem
= divmod(xe
, n
)
1915 # compute nth root of xc using Newton's method
1916 a
= 1L << -(-_nbits(xc
)//n
) # initial estimate
1918 q
, r
= divmod(xc
, a
**(n
-1))
1922 a
= (a
*(n
-1) + q
)//n
1923 if not (a
== q
and r
== 0):
1927 # now xc*10**xe is the nth root of the original xc*10**xe
1928 # compute mth power of xc*10**xe
1930 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1931 # 10**p and the result is not representable.
1932 if xc
> 1 and m
> p
*100//_log10_lb(xc
):
1939 # by this point the result *is* exactly representable
1940 # adjust the exponent to get as close as possible to the ideal
1941 # exponent, if necessary
1943 if other
._isinteger
() and other
._sign
== 0:
1944 ideal_exponent
= self
._exp
*int(other
)
1945 zeros
= min(xe
-ideal_exponent
, p
-len(str_xc
))
1948 return _dec_from_triple(0, str_xc
+'0'*zeros
, xe
-zeros
)
1950 def __pow__(self
, other
, modulo
=None, context
=None):
1951 """Return self ** other [ % modulo].
1953 With two arguments, compute self**other.
1955 With three arguments, compute (self**other) % modulo. For the
1956 three argument form, the following restrictions on the
1959 - all three arguments must be integral
1960 - other must be nonnegative
1961 - either self or other (or both) must be nonzero
1962 - modulo must be nonzero and must have at most p digits,
1963 where p is the context precision.
1965 If any of these restrictions is violated the InvalidOperation
1968 The result of pow(self, other, modulo) is identical to the
1969 result that would be obtained by computing (self**other) %
1970 modulo with unbounded precision, but is computed more
1971 efficiently. It is always exact.
1974 if modulo
is not None:
1975 return self
._power
_modulo
(other
, modulo
, context
)
1977 other
= _convert_other(other
)
1978 if other
is NotImplemented:
1982 context
= getcontext()
1984 # either argument is a NaN => result is NaN
1985 ans
= self
._check
_nans
(other
, context
)
1989 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1992 return context
._raise
_error
(InvalidOperation
, '0 ** 0')
1996 # result has sign 1 iff self._sign is 1 and other is an odd integer
1999 if other
._isinteger
():
2000 if not other
._iseven
():
2003 # -ve**noninteger = NaN
2004 # (-0)**noninteger = 0**noninteger
2006 return context
._raise
_error
(InvalidOperation
,
2007 'x ** y with x negative and y not an integer')
2008 # negate self, without doing any unwanted rounding
2009 self
= self
.copy_negate()
2011 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2013 if other
._sign
== 0:
2014 return _dec_from_triple(result_sign
, '0', 0)
2016 return Infsign
[result_sign
]
2018 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2019 if self
._isinfinity
():
2020 if other
._sign
== 0:
2021 return Infsign
[result_sign
]
2023 return _dec_from_triple(result_sign
, '0', 0)
2025 # 1**other = 1, but the choice of exponent and the flags
2026 # depend on the exponent of self, and on whether other is a
2027 # positive integer, a negative integer, or neither
2029 if other
._isinteger
():
2030 # exp = max(self._exp*max(int(other), 0),
2031 # 1-context.prec) but evaluating int(other) directly
2032 # is dangerous until we know other is small (other
2033 # could be 1e999999999)
2034 if other
._sign
== 1:
2036 elif other
> context
.prec
:
2037 multiplier
= context
.prec
2039 multiplier
= int(other
)
2041 exp
= self
._exp
* multiplier
2042 if exp
< 1-context
.prec
:
2043 exp
= 1-context
.prec
2044 context
._raise
_error
(Rounded
)
2046 context
._raise
_error
(Inexact
)
2047 context
._raise
_error
(Rounded
)
2048 exp
= 1-context
.prec
2050 return _dec_from_triple(result_sign
, '1'+'0'*-exp
, exp
)
2052 # compute adjusted exponent of self
2053 self_adj
= self
.adjusted()
2055 # self ** infinity is infinity if self > 1, 0 if self < 1
2056 # self ** -infinity is infinity if self < 1, 0 if self > 1
2057 if other
._isinfinity
():
2058 if (other
._sign
== 0) == (self_adj
< 0):
2059 return _dec_from_triple(result_sign
, '0', 0)
2061 return Infsign
[result_sign
]
2063 # from here on, the result always goes through the call
2064 # to _fix at the end of this function.
2067 # crude test to catch cases of extreme overflow/underflow. If
2068 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2069 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2070 # self**other >= 10**(Emax+1), so overflow occurs. The test
2071 # for underflow is similar.
2072 bound
= self
._log
10_exp
_bound
() + other
.adjusted()
2073 if (self_adj
>= 0) == (other
._sign
== 0):
2074 # self > 1 and other +ve, or self < 1 and other -ve
2075 # possibility of overflow
2076 if bound
>= len(str(context
.Emax
)):
2077 ans
= _dec_from_triple(result_sign
, '1', context
.Emax
+1)
2079 # self > 1 and other -ve, or self < 1 and other +ve
2080 # possibility of underflow to 0
2081 Etiny
= context
.Etiny()
2082 if bound
>= len(str(-Etiny
)):
2083 ans
= _dec_from_triple(result_sign
, '1', Etiny
-1)
2085 # try for an exact result with precision +1
2087 ans
= self
._power
_exact
(other
, context
.prec
+ 1)
2088 if ans
is not None and result_sign
== 1:
2089 ans
= _dec_from_triple(1, ans
._int
, ans
._exp
)
2091 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2095 xc
, xe
= x
.int, x
.exp
2097 yc
, ye
= y
.int, y
.exp
2101 # compute correctly rounded result: start with precision +3,
2102 # then increase precision until result is unambiguously roundable
2105 coeff
, exp
= _dpower(xc
, xe
, yc
, ye
, p
+extra
)
2106 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
2110 ans
= _dec_from_triple(result_sign
, str(coeff
), exp
)
2112 # the specification says that for non-integer other we need to
2113 # raise Inexact, even when the result is actually exact. In
2114 # the same way, we need to raise Underflow here if the result
2115 # is subnormal. (The call to _fix will take care of raising
2116 # Rounded and Subnormal, as usual.)
2117 if not other
._isinteger
():
2118 context
._raise
_error
(Inexact
)
2119 # pad with zeros up to length context.prec+1 if necessary
2120 if len(ans
._int
) <= context
.prec
:
2121 expdiff
= context
.prec
+1 - len(ans
._int
)
2122 ans
= _dec_from_triple(ans
._sign
, ans
._int
+'0'*expdiff
,
2124 if ans
.adjusted() < context
.Emin
:
2125 context
._raise
_error
(Underflow
)
2127 # unlike exp, ln and log10, the power function respects the
2128 # rounding mode; no need to use ROUND_HALF_EVEN here
2129 ans
= ans
._fix
(context
)
2132 def __rpow__(self
, other
, context
=None):
2133 """Swaps self/other and returns __pow__."""
2134 other
= _convert_other(other
)
2135 if other
is NotImplemented:
2137 return other
.__pow
__(self
, context
=context
)
2139 def normalize(self
, context
=None):
2140 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2143 context
= getcontext()
2145 if self
._is
_special
:
2146 ans
= self
._check
_nans
(context
=context
)
2150 dup
= self
._fix
(context
)
2151 if dup
._isinfinity
():
2155 return _dec_from_triple(dup
._sign
, '0', 0)
2156 exp_max
= [context
.Emax
, context
.Etop()][context
._clamp
]
2159 while dup
._int
[end
-1] == '0' and exp
< exp_max
:
2162 return _dec_from_triple(dup
._sign
, dup
._int
[:end
], exp
)
2164 def quantize(self
, exp
, rounding
=None, context
=None, watchexp
=True):
2165 """Quantize self so its exponent is the same as that of exp.
2167 Similar to self._rescale(exp._exp) but with error checking.
2169 exp
= _convert_other(exp
, raiseit
=True)
2172 context
= getcontext()
2173 if rounding
is None:
2174 rounding
= context
.rounding
2176 if self
._is
_special
or exp
._is
_special
:
2177 ans
= self
._check
_nans
(exp
, context
)
2181 if exp
._isinfinity
() or self
._isinfinity
():
2182 if exp
._isinfinity
() and self
._isinfinity
():
2183 return Decimal(self
) # if both are inf, it is OK
2184 return context
._raise
_error
(InvalidOperation
,
2185 'quantize with one INF')
2187 # if we're not watching exponents, do a simple rescale
2189 ans
= self
._rescale
(exp
._exp
, rounding
)
2190 # raise Inexact and Rounded where appropriate
2191 if ans
._exp
> self
._exp
:
2192 context
._raise
_error
(Rounded
)
2194 context
._raise
_error
(Inexact
)
2197 # exp._exp should be between Etiny and Emax
2198 if not (context
.Etiny() <= exp
._exp
<= context
.Emax
):
2199 return context
._raise
_error
(InvalidOperation
,
2200 'target exponent out of bounds in quantize')
2203 ans
= _dec_from_triple(self
._sign
, '0', exp
._exp
)
2204 return ans
._fix
(context
)
2206 self_adjusted
= self
.adjusted()
2207 if self_adjusted
> context
.Emax
:
2208 return context
._raise
_error
(InvalidOperation
,
2209 'exponent of quantize result too large for current context')
2210 if self_adjusted
- exp
._exp
+ 1 > context
.prec
:
2211 return context
._raise
_error
(InvalidOperation
,
2212 'quantize result has too many digits for current context')
2214 ans
= self
._rescale
(exp
._exp
, rounding
)
2215 if ans
.adjusted() > context
.Emax
:
2216 return context
._raise
_error
(InvalidOperation
,
2217 'exponent of quantize result too large for current context')
2218 if len(ans
._int
) > context
.prec
:
2219 return context
._raise
_error
(InvalidOperation
,
2220 'quantize result has too many digits for current context')
2222 # raise appropriate flags
2223 if ans
._exp
> self
._exp
:
2224 context
._raise
_error
(Rounded
)
2226 context
._raise
_error
(Inexact
)
2227 if ans
and ans
.adjusted() < context
.Emin
:
2228 context
._raise
_error
(Subnormal
)
2230 # call to fix takes care of any necessary folddown
2231 ans
= ans
._fix
(context
)
2234 def same_quantum(self
, other
):
2235 """Return True if self and other have the same exponent; otherwise
2238 If either operand is a special value, the following rules are used:
2239 * return True if both operands are infinities
2240 * return True if both operands are NaNs
2241 * otherwise, return False.
2243 other
= _convert_other(other
, raiseit
=True)
2244 if self
._is
_special
or other
._is
_special
:
2245 return (self
.is_nan() and other
.is_nan() or
2246 self
.is_infinite() and other
.is_infinite())
2247 return self
._exp
== other
._exp
2249 def _rescale(self
, exp
, rounding
):
2250 """Rescale self so that the exponent is exp, either by padding with zeros
2251 or by truncating digits, using the given rounding mode.
2253 Specials are returned without change. This operation is
2254 quiet: it raises no flags, and uses no information from the
2257 exp = exp to scale to (an integer)
2258 rounding = rounding mode
2260 if self
._is
_special
:
2261 return Decimal(self
)
2263 return _dec_from_triple(self
._sign
, '0', exp
)
2265 if self
._exp
>= exp
:
2266 # pad answer with zeros if necessary
2267 return _dec_from_triple(self
._sign
,
2268 self
._int
+ '0'*(self
._exp
- exp
), exp
)
2270 # too many digits; round and lose data. If self.adjusted() <
2271 # exp-1, replace self by 10**(exp-1) before rounding
2272 digits
= len(self
._int
) + self
._exp
- exp
2274 self
= _dec_from_triple(self
._sign
, '1', exp
-1)
2276 this_function
= getattr(self
, self
._pick
_rounding
_function
[rounding
])
2277 changed
= this_function(digits
)
2278 coeff
= self
._int
[:digits
] or '0'
2280 coeff
= str(int(coeff
)+1)
2281 return _dec_from_triple(self
._sign
, coeff
, exp
)
2283 def to_integral_exact(self
, rounding
=None, context
=None):
2284 """Rounds to a nearby integer.
2286 If no rounding mode is specified, take the rounding mode from
2287 the context. This method raises the Rounded and Inexact flags
2290 See also: to_integral_value, which does exactly the same as
2291 this method except that it doesn't raise Inexact or Rounded.
2293 if self
._is
_special
:
2294 ans
= self
._check
_nans
(context
=context
)
2297 return Decimal(self
)
2299 return Decimal(self
)
2301 return _dec_from_triple(self
._sign
, '0', 0)
2303 context
= getcontext()
2304 if rounding
is None:
2305 rounding
= context
.rounding
2306 context
._raise
_error
(Rounded
)
2307 ans
= self
._rescale
(0, rounding
)
2309 context
._raise
_error
(Inexact
)
2312 def to_integral_value(self
, rounding
=None, context
=None):
2313 """Rounds to the nearest integer, without raising inexact, rounded."""
2315 context
= getcontext()
2316 if rounding
is None:
2317 rounding
= context
.rounding
2318 if self
._is
_special
:
2319 ans
= self
._check
_nans
(context
=context
)
2322 return Decimal(self
)
2324 return Decimal(self
)
2326 return self
._rescale
(0, rounding
)
2328 # the method name changed, but we provide also the old one, for compatibility
2329 to_integral
= to_integral_value
2331 def sqrt(self
, context
=None):
2332 """Return the square root of self."""
2333 if self
._is
_special
:
2334 ans
= self
._check
_nans
(context
=context
)
2338 if self
._isinfinity
() and self
._sign
== 0:
2339 return Decimal(self
)
2342 # exponent = self._exp // 2. sqrt(-0) = -0
2343 ans
= _dec_from_triple(self
._sign
, '0', self
._exp
// 2)
2344 return ans
._fix
(context
)
2347 context
= getcontext()
2350 return context
._raise
_error
(InvalidOperation
, 'sqrt(-x), x > 0')
2352 # At this point self represents a positive number. Let p be
2353 # the desired precision and express self in the form c*100**e
2354 # with c a positive real number and e an integer, c and e
2355 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2356 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2357 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2358 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2359 # the closest integer to sqrt(c) with the even integer chosen
2360 # in the case of a tie.
2362 # To ensure correct rounding in all cases, we use the
2363 # following trick: we compute the square root to an extra
2364 # place (precision p+1 instead of precision p), rounding down.
2365 # Then, if the result is inexact and its last digit is 0 or 5,
2366 # we increase the last digit to 1 or 6 respectively; if it's
2367 # exact we leave the last digit alone. Now the final round to
2368 # p places (or fewer in the case of underflow) will round
2369 # correctly and raise the appropriate flags.
2371 # use an extra digit of precision
2372 prec
= context
.prec
+1
2374 # write argument in the form c*100**e where e = self._exp//2
2375 # is the 'ideal' exponent, to be used if the square root is
2376 # exactly representable. l is the number of 'digits' of c in
2377 # base 100, so that 100**(l-1) <= c < 100**l.
2382 l
= (len(self
._int
) >> 1) + 1
2385 l
= len(self
._int
)+1 >> 1
2387 # rescale so that c has exactly prec base 100 'digits'
2393 c
, remainder
= divmod(c
, 100**-shift
)
2394 exact
= not remainder
2397 # find n = floor(sqrt(c)) using Newton's method
2405 exact
= exact
and n
*n
== c
2408 # result is exact; rescale to use ideal exponent e
2410 # assert n % 10**shift == 0
2416 # result is not exact; fix last digit as described above
2420 ans
= _dec_from_triple(0, str(n
), e
)
2422 # round, and fit to current context
2423 context
= context
._shallow
_copy
()
2424 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2425 ans
= ans
._fix
(context
)
2426 context
.rounding
= rounding
2430 def max(self
, other
, context
=None):
2431 """Returns the larger value.
2433 Like max(self, other) except if one is not a number, returns
2434 NaN (and signals if one is sNaN). Also rounds.
2436 other
= _convert_other(other
, raiseit
=True)
2439 context
= getcontext()
2441 if self
._is
_special
or other
._is
_special
:
2442 # If one operand is a quiet NaN and the other is number, then the
2443 # number is always returned
2447 if on
== 1 and sn
!= 2:
2448 return self
._fix
_nan
(context
)
2449 if sn
== 1 and on
!= 2:
2450 return other
._fix
_nan
(context
)
2451 return self
._check
_nans
(other
, context
)
2453 c
= self
.__cmp
__(other
)
2455 # If both operands are finite and equal in numerical value
2456 # then an ordering is applied:
2458 # If the signs differ then max returns the operand with the
2459 # positive sign and min returns the operand with the negative sign
2461 # If the signs are the same then the exponent is used to select
2462 # the result. This is exactly the ordering used in compare_total.
2463 c
= self
.compare_total(other
)
2470 return ans
._fix
(context
)
2472 def min(self
, other
, context
=None):
2473 """Returns the smaller value.
2475 Like min(self, other) except if one is not a number, returns
2476 NaN (and signals if one is sNaN). Also rounds.
2478 other
= _convert_other(other
, raiseit
=True)
2481 context
= getcontext()
2483 if self
._is
_special
or other
._is
_special
:
2484 # If one operand is a quiet NaN and the other is number, then the
2485 # number is always returned
2489 if on
== 1 and sn
!= 2:
2490 return self
._fix
_nan
(context
)
2491 if sn
== 1 and on
!= 2:
2492 return other
._fix
_nan
(context
)
2493 return self
._check
_nans
(other
, context
)
2495 c
= self
.__cmp
__(other
)
2497 c
= self
.compare_total(other
)
2504 return ans
._fix
(context
)
2506 def _isinteger(self
):
2507 """Returns whether self is an integer"""
2508 if self
._is
_special
:
2512 rest
= self
._int
[self
._exp
:]
2513 return rest
== '0'*len(rest
)
2516 """Returns True if self is even. Assumes self is an integer."""
2517 if not self
or self
._exp
> 0:
2519 return self
._int
[-1+self
._exp
] in '02468'
2522 """Return the adjusted exponent of self"""
2524 return self
._exp
+ len(self
._int
) - 1
2525 # If NaN or Infinity, self._exp is string
2529 def canonical(self
, context
=None):
2530 """Returns the same Decimal object.
2532 As we do not have different encodings for the same number, the
2533 received object already is in its canonical form.
2537 def compare_signal(self
, other
, context
=None):
2538 """Compares self to the other operand numerically.
2540 It's pretty much like compare(), but all NaNs signal, with signaling
2541 NaNs taking precedence over quiet NaNs.
2544 context
= getcontext()
2546 self_is_nan
= self
._isnan
()
2547 other_is_nan
= other
._isnan
()
2548 if self_is_nan
== 2:
2549 return context
._raise
_error
(InvalidOperation
, 'sNaN',
2551 if other_is_nan
== 2:
2552 return context
._raise
_error
(InvalidOperation
, 'sNaN',
2555 return context
._raise
_error
(InvalidOperation
, 'NaN in compare_signal',
2558 return context
._raise
_error
(InvalidOperation
, 'NaN in compare_signal',
2560 return self
.compare(other
, context
=context
)
2562 def compare_total(self
, other
):
2563 """Compares self to other using the abstract representations.
2565 This is not like the standard compare, which use their numerical
2566 value. Note that a total ordering is defined for all possible abstract
2569 # if one is negative and the other is positive, it's easy
2570 if self
._sign
and not other
._sign
:
2572 if not self
._sign
and other
._sign
:
2576 # let's handle both NaN types
2577 self_nan
= self
._isnan
()
2578 other_nan
= other
._isnan
()
2579 if self_nan
or other_nan
:
2580 if self_nan
== other_nan
:
2581 if self
._int
< other
._int
:
2586 if self
._int
> other
._int
:
2617 if self
._exp
< other
._exp
:
2622 if self
._exp
> other
._exp
:
2630 def compare_total_mag(self
, other
):
2631 """Compares self to other using abstract repr., ignoring sign.
2633 Like compare_total, but with operand's sign ignored and assumed to be 0.
2636 o
= other
.copy_abs()
2637 return s
.compare_total(o
)
2640 """Returns a copy with the sign set to 0. """
2641 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
2643 def copy_negate(self
):
2644 """Returns a copy with the sign inverted."""
2646 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
2648 return _dec_from_triple(1, self
._int
, self
._exp
, self
._is
_special
)
2650 def copy_sign(self
, other
):
2651 """Returns self with the sign of other."""
2652 return _dec_from_triple(other
._sign
, self
._int
,
2653 self
._exp
, self
._is
_special
)
2655 def exp(self
, context
=None):
2656 """Returns e ** self."""
2659 context
= getcontext()
2662 ans
= self
._check
_nans
(context
=context
)
2666 # exp(-Infinity) = 0
2667 if self
._isinfinity
() == -1:
2674 # exp(Infinity) = Infinity
2675 if self
._isinfinity
() == 1:
2676 return Decimal(self
)
2678 # the result is now guaranteed to be inexact (the true
2679 # mathematical result is transcendental). There's no need to
2680 # raise Rounded and Inexact here---they'll always be raised as
2681 # a result of the call to _fix.
2683 adj
= self
.adjusted()
2685 # we only need to do any computation for quite a small range
2686 # of adjusted exponents---for example, -29 <= adj <= 10 for
2687 # the default context. For smaller exponent the result is
2688 # indistinguishable from 1 at the given precision, while for
2689 # larger exponent the result either overflows or underflows.
2690 if self
._sign
== 0 and adj
> len(str((context
.Emax
+1)*3)):
2692 ans
= _dec_from_triple(0, '1', context
.Emax
+1)
2693 elif self
._sign
== 1 and adj
> len(str((-context
.Etiny()+1)*3)):
2695 ans
= _dec_from_triple(0, '1', context
.Etiny()-1)
2696 elif self
._sign
== 0 and adj
< -p
:
2697 # p+1 digits; final round will raise correct flags
2698 ans
= _dec_from_triple(0, '1' + '0'*(p
-1) + '1', -p
)
2699 elif self
._sign
== 1 and adj
< -p
-1:
2700 # p+1 digits; final round will raise correct flags
2701 ans
= _dec_from_triple(0, '9'*(p
+1), -p
-1)
2705 c
, e
= op
.int, op
.exp
2709 # compute correctly rounded result: increase precision by
2710 # 3 digits at a time until we get an unambiguously
2714 coeff
, exp
= _dexp(c
, e
, p
+extra
)
2715 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
2719 ans
= _dec_from_triple(0, str(coeff
), exp
)
2721 # at this stage, ans should round correctly with *any*
2722 # rounding mode, not just with ROUND_HALF_EVEN
2723 context
= context
._shallow
_copy
()
2724 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2725 ans
= ans
._fix
(context
)
2726 context
.rounding
= rounding
2730 def is_canonical(self
):
2731 """Return True if self is canonical; otherwise return False.
2733 Currently, the encoding of a Decimal instance is always
2734 canonical, so this method returns True for any Decimal.
2738 def is_finite(self
):
2739 """Return True if self is finite; otherwise return False.
2741 A Decimal instance is considered finite if it is neither
2744 return not self
._is
_special
2746 def is_infinite(self
):
2747 """Return True if self is infinite; otherwise return False."""
2748 return self
._exp
== 'F'
2751 """Return True if self is a qNaN or sNaN; otherwise return False."""
2752 return self
._exp
in ('n', 'N')
2754 def is_normal(self
, context
=None):
2755 """Return True if self is a normal number; otherwise return False."""
2756 if self
._is
_special
or not self
:
2759 context
= getcontext()
2760 return context
.Emin
<= self
.adjusted() <= context
.Emax
2763 """Return True if self is a quiet NaN; otherwise return False."""
2764 return self
._exp
== 'n'
2766 def is_signed(self
):
2767 """Return True if self is negative; otherwise return False."""
2768 return self
._sign
== 1
2771 """Return True if self is a signaling NaN; otherwise return False."""
2772 return self
._exp
== 'N'
2774 def is_subnormal(self
, context
=None):
2775 """Return True if self is subnormal; otherwise return False."""
2776 if self
._is
_special
or not self
:
2779 context
= getcontext()
2780 return self
.adjusted() < context
.Emin
2783 """Return True if self is a zero; otherwise return False."""
2784 return not self
._is
_special
and self
._int
== '0'
2786 def _ln_exp_bound(self
):
2787 """Compute a lower bound for the adjusted exponent of self.ln().
2788 In other words, compute r such that self.ln() >= 10**r. Assumes
2789 that self is finite and positive and that self != 1.
2792 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2793 adj
= self
._exp
+ len(self
._int
) - 1
2795 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2796 return len(str(adj
*23//10)) - 1
2799 return len(str((-1-adj
)*23//10)) - 1
2801 c
, e
= op
.int, op
.exp
2806 return len(num
) - len(den
) - (num
< den
)
2807 # adj == -1, 0.1 <= self < 1
2808 return e
+ len(str(10**-e
- c
)) - 1
2811 def ln(self
, context
=None):
2812 """Returns the natural (base e) logarithm of self."""
2815 context
= getcontext()
2818 ans
= self
._check
_nans
(context
=context
)
2822 # ln(0.0) == -Infinity
2826 # ln(Infinity) = Infinity
2827 if self
._isinfinity
() == 1:
2834 # ln(negative) raises InvalidOperation
2836 return context
._raise
_error
(InvalidOperation
,
2837 'ln of a negative value')
2839 # result is irrational, so necessarily inexact
2841 c
, e
= op
.int, op
.exp
2844 # correctly rounded result: repeatedly increase precision by 3
2845 # until we get an unambiguously roundable result
2846 places
= p
- self
._ln
_exp
_bound
() + 2 # at least p+3 places
2848 coeff
= _dlog(c
, e
, places
)
2849 # assert len(str(abs(coeff)))-p >= 1
2850 if coeff
% (5*10**(len(str(abs(coeff
)))-p
-1)):
2853 ans
= _dec_from_triple(int(coeff
<0), str(abs(coeff
)), -places
)
2855 context
= context
._shallow
_copy
()
2856 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2857 ans
= ans
._fix
(context
)
2858 context
.rounding
= rounding
2861 def _log10_exp_bound(self
):
2862 """Compute a lower bound for the adjusted exponent of self.log10().
2863 In other words, find r such that self.log10() >= 10**r.
2864 Assumes that self is finite and positive and that self != 1.
2867 # For x >= 10 or x < 0.1 we only need a bound on the integer
2868 # part of log10(self), and this comes directly from the
2869 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2870 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2871 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2873 adj
= self
._exp
+ len(self
._int
) - 1
2876 return len(str(adj
))-1
2879 return len(str(-1-adj
))-1
2881 c
, e
= op
.int, op
.exp
2886 return len(num
) - len(den
) - (num
< den
) + 2
2887 # adj == -1, 0.1 <= self < 1
2889 return len(num
) + e
- (num
< "231") - 1
2891 def log10(self
, context
=None):
2892 """Returns the base 10 logarithm of self."""
2895 context
= getcontext()
2898 ans
= self
._check
_nans
(context
=context
)
2902 # log10(0.0) == -Infinity
2906 # log10(Infinity) = Infinity
2907 if self
._isinfinity
() == 1:
2910 # log10(negative or -Infinity) raises InvalidOperation
2912 return context
._raise
_error
(InvalidOperation
,
2913 'log10 of a negative value')
2916 if self
._int
[0] == '1' and self
._int
[1:] == '0'*(len(self
._int
) - 1):
2917 # answer may need rounding
2918 ans
= Decimal(self
._exp
+ len(self
._int
) - 1)
2920 # result is irrational, so necessarily inexact
2922 c
, e
= op
.int, op
.exp
2925 # correctly rounded result: repeatedly increase precision
2926 # until result is unambiguously roundable
2927 places
= p
-self
._log
10_exp
_bound
()+2
2929 coeff
= _dlog10(c
, e
, places
)
2930 # assert len(str(abs(coeff)))-p >= 1
2931 if coeff
% (5*10**(len(str(abs(coeff
)))-p
-1)):
2934 ans
= _dec_from_triple(int(coeff
<0), str(abs(coeff
)), -places
)
2936 context
= context
._shallow
_copy
()
2937 rounding
= context
._set
_rounding
(ROUND_HALF_EVEN
)
2938 ans
= ans
._fix
(context
)
2939 context
.rounding
= rounding
2942 def logb(self
, context
=None):
2943 """ Returns the exponent of the magnitude of self's MSD.
2945 The result is the integer which is the exponent of the magnitude
2946 of the most significant digit of self (as though it were truncated
2947 to a single digit while maintaining the value of that digit and
2948 without limiting the resulting exponent).
2951 ans
= self
._check
_nans
(context
=context
)
2956 context
= getcontext()
2958 # logb(+/-Inf) = +Inf
2959 if self
._isinfinity
():
2962 # logb(0) = -Inf, DivisionByZero
2964 return context
._raise
_error
(DivisionByZero
, 'logb(0)', 1)
2966 # otherwise, simply return the adjusted exponent of self, as a
2967 # Decimal. Note that no attempt is made to fit the result
2968 # into the current context.
2969 return Decimal(self
.adjusted())
2971 def _islogical(self
):
2972 """Return True if self is a logical operand.
2974 For being logical, it must be a finite number with a sign of 0,
2975 an exponent of 0, and a coefficient whose digits must all be
2978 if self
._sign
!= 0 or self
._exp
!= 0:
2980 for dig
in self
._int
:
2985 def _fill_logical(self
, context
, opa
, opb
):
2986 dif
= context
.prec
- len(opa
)
2990 opa
= opa
[-context
.prec
:]
2991 dif
= context
.prec
- len(opb
)
2995 opb
= opb
[-context
.prec
:]
2998 def logical_and(self
, other
, context
=None):
2999 """Applies an 'and' operation between self and other's digits."""
3001 context
= getcontext()
3002 if not self
._islogical
() or not other
._islogical
():
3003 return context
._raise
_error
(InvalidOperation
)
3005 # fill to context.prec
3006 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3008 # make the operation, and clean starting zeroes
3009 result
= "".join([str(int(a
)&int(b
)) for a
,b
in zip(opa
,opb
)])
3010 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3012 def logical_invert(self
, context
=None):
3013 """Invert all its digits."""
3015 context
= getcontext()
3016 return self
.logical_xor(_dec_from_triple(0,'1'*context
.prec
,0),
3019 def logical_or(self
, other
, context
=None):
3020 """Applies an 'or' operation between self and other's digits."""
3022 context
= getcontext()
3023 if not self
._islogical
() or not other
._islogical
():
3024 return context
._raise
_error
(InvalidOperation
)
3026 # fill to context.prec
3027 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3029 # make the operation, and clean starting zeroes
3030 result
= "".join(str(int(a
)|
int(b
)) for a
,b
in zip(opa
,opb
))
3031 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3033 def logical_xor(self
, other
, context
=None):
3034 """Applies an 'xor' operation between self and other's digits."""
3036 context
= getcontext()
3037 if not self
._islogical
() or not other
._islogical
():
3038 return context
._raise
_error
(InvalidOperation
)
3040 # fill to context.prec
3041 (opa
, opb
) = self
._fill
_logical
(context
, self
._int
, other
._int
)
3043 # make the operation, and clean starting zeroes
3044 result
= "".join(str(int(a
)^
int(b
)) for a
,b
in zip(opa
,opb
))
3045 return _dec_from_triple(0, result
.lstrip('0') or '0', 0)
3047 def max_mag(self
, other
, context
=None):
3048 """Compares the values numerically with their sign ignored."""
3049 other
= _convert_other(other
, raiseit
=True)
3052 context
= getcontext()
3054 if self
._is
_special
or other
._is
_special
:
3055 # If one operand is a quiet NaN and the other is number, then the
3056 # number is always returned
3060 if on
== 1 and sn
!= 2:
3061 return self
._fix
_nan
(context
)
3062 if sn
== 1 and on
!= 2:
3063 return other
._fix
_nan
(context
)
3064 return self
._check
_nans
(other
, context
)
3066 c
= self
.copy_abs().__cmp
__(other
.copy_abs())
3068 c
= self
.compare_total(other
)
3075 return ans
._fix
(context
)
3077 def min_mag(self
, other
, context
=None):
3078 """Compares the values numerically with their sign ignored."""
3079 other
= _convert_other(other
, raiseit
=True)
3082 context
= getcontext()
3084 if self
._is
_special
or other
._is
_special
:
3085 # If one operand is a quiet NaN and the other is number, then the
3086 # number is always returned
3090 if on
== 1 and sn
!= 2:
3091 return self
._fix
_nan
(context
)
3092 if sn
== 1 and on
!= 2:
3093 return other
._fix
_nan
(context
)
3094 return self
._check
_nans
(other
, context
)
3096 c
= self
.copy_abs().__cmp
__(other
.copy_abs())
3098 c
= self
.compare_total(other
)
3105 return ans
._fix
(context
)
3107 def next_minus(self
, context
=None):
3108 """Returns the largest representable number smaller than itself."""
3110 context
= getcontext()
3112 ans
= self
._check
_nans
(context
=context
)
3116 if self
._isinfinity
() == -1:
3118 if self
._isinfinity
() == 1:
3119 return _dec_from_triple(0, '9'*context
.prec
, context
.Etop())
3121 context
= context
.copy()
3122 context
._set
_rounding
(ROUND_FLOOR
)
3123 context
._ignore
_all
_flags
()
3124 new_self
= self
._fix
(context
)
3125 if new_self
!= self
:
3127 return self
.__sub
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3130 def next_plus(self
, context
=None):
3131 """Returns the smallest representable number larger than itself."""
3133 context
= getcontext()
3135 ans
= self
._check
_nans
(context
=context
)
3139 if self
._isinfinity
() == 1:
3141 if self
._isinfinity
() == -1:
3142 return _dec_from_triple(1, '9'*context
.prec
, context
.Etop())
3144 context
= context
.copy()
3145 context
._set
_rounding
(ROUND_CEILING
)
3146 context
._ignore
_all
_flags
()
3147 new_self
= self
._fix
(context
)
3148 if new_self
!= self
:
3150 return self
.__add
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3153 def next_toward(self
, other
, context
=None):
3154 """Returns the number closest to self, in the direction towards other.
3156 The result is the closest representable number to self
3157 (excluding self) that is in the direction towards other,
3158 unless both have the same value. If the two operands are
3159 numerically equal, then the result is a copy of self with the
3160 sign set to be the same as the sign of other.
3162 other
= _convert_other(other
, raiseit
=True)
3165 context
= getcontext()
3167 ans
= self
._check
_nans
(other
, context
)
3171 comparison
= self
.__cmp
__(other
)
3173 return self
.copy_sign(other
)
3175 if comparison
== -1:
3176 ans
= self
.next_plus(context
)
3177 else: # comparison == 1
3178 ans
= self
.next_minus(context
)
3180 # decide which flags to raise using value of ans
3181 if ans
._isinfinity
():
3182 context
._raise
_error
(Overflow
,
3183 'Infinite result from next_toward',
3185 context
._raise
_error
(Rounded
)
3186 context
._raise
_error
(Inexact
)
3187 elif ans
.adjusted() < context
.Emin
:
3188 context
._raise
_error
(Underflow
)
3189 context
._raise
_error
(Subnormal
)
3190 context
._raise
_error
(Rounded
)
3191 context
._raise
_error
(Inexact
)
3192 # if precision == 1 then we don't raise Clamped for a
3195 context
._raise
_error
(Clamped
)
3199 def number_class(self
, context
=None):
3200 """Returns an indication of the class of self.
3202 The class is one of the following strings:
3218 inf
= self
._isinfinity
()
3229 context
= getcontext()
3230 if self
.is_subnormal(context
=context
):
3235 # just a normal, regular, boring number, :)
3242 """Just returns 10, as this is Decimal, :)"""
3245 def rotate(self
, other
, context
=None):
3246 """Returns a rotated copy of self, value-of-other times."""
3248 context
= getcontext()
3250 ans
= self
._check
_nans
(other
, context
)
3255 return context
._raise
_error
(InvalidOperation
)
3256 if not (-context
.prec
<= int(other
) <= context
.prec
):
3257 return context
._raise
_error
(InvalidOperation
)
3259 if self
._isinfinity
():
3260 return Decimal(self
)
3262 # get values, pad if necessary
3265 topad
= context
.prec
- len(rotdig
)
3267 rotdig
= '0'*topad
+ rotdig
3270 rotated
= rotdig
[torot
:] + rotdig
[:torot
]
3271 return _dec_from_triple(self
._sign
,
3272 rotated
.lstrip('0') or '0', self
._exp
)
3274 def scaleb (self
, other
, context
=None):
3275 """Returns self operand after adding the second value to its exp."""
3277 context
= getcontext()
3279 ans
= self
._check
_nans
(other
, context
)
3284 return context
._raise
_error
(InvalidOperation
)
3285 liminf
= -2 * (context
.Emax
+ context
.prec
)
3286 limsup
= 2 * (context
.Emax
+ context
.prec
)
3287 if not (liminf
<= int(other
) <= limsup
):
3288 return context
._raise
_error
(InvalidOperation
)
3290 if self
._isinfinity
():
3291 return Decimal(self
)
3293 d
= _dec_from_triple(self
._sign
, self
._int
, self
._exp
+ int(other
))
3297 def shift(self
, other
, context
=None):
3298 """Returns a shifted copy of self, value-of-other times."""
3300 context
= getcontext()
3302 ans
= self
._check
_nans
(other
, context
)
3307 return context
._raise
_error
(InvalidOperation
)
3308 if not (-context
.prec
<= int(other
) <= context
.prec
):
3309 return context
._raise
_error
(InvalidOperation
)
3311 if self
._isinfinity
():
3312 return Decimal(self
)
3314 # get values, pad if necessary
3317 return Decimal(self
)
3319 topad
= context
.prec
- len(rotdig
)
3321 rotdig
= '0'*topad
+ rotdig
3325 rotated
= rotdig
[:torot
]
3327 rotated
= rotdig
+ '0'*torot
3328 rotated
= rotated
[-context
.prec
:]
3330 return _dec_from_triple(self
._sign
,
3331 rotated
.lstrip('0') or '0', self
._exp
)
3333 # Support for pickling, copy, and deepcopy
3334 def __reduce__(self
):
3335 return (self
.__class
__, (str(self
),))
3338 if type(self
) == Decimal
:
3339 return self
# I'm immutable; therefore I am my own clone
3340 return self
.__class
__(str(self
))
3342 def __deepcopy__(self
, memo
):
3343 if type(self
) == Decimal
:
3344 return self
# My components are also immutable
3345 return self
.__class
__(str(self
))
3347 def _dec_from_triple(sign
, coefficient
, exponent
, special
=False):
3348 """Create a decimal instance directly, without any validation,
3349 normalization (e.g. removal of leading zeros) or argument
3352 This function is for *internal use only*.
3355 self
= object.__new
__(Decimal
)
3357 self
._int
= coefficient
3358 self
._exp
= exponent
3359 self
._is
_special
= special
3363 ##### Context class #######################################################
3366 # get rounding method function:
3367 rounding_functions
= [name
for name
in Decimal
.__dict
__.keys()
3368 if name
.startswith('_round_')]
3369 for name
in rounding_functions
:
3370 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3371 globalname
= name
[1:].upper()
3372 val
= globals()[globalname
]
3373 Decimal
._pick
_rounding
_function
[val
] = name
3375 del name
, val
, globalname
, rounding_functions
3377 class _ContextManager(object):
3378 """Context manager class to support localcontext().
3380 Sets a copy of the supplied context in __enter__() and restores
3381 the previous decimal context in __exit__()
3383 def __init__(self
, new_context
):
3384 self
.new_context
= new_context
.copy()
3385 def __enter__(self
):
3386 self
.saved_context
= getcontext()
3387 setcontext(self
.new_context
)
3388 return self
.new_context
3389 def __exit__(self
, t
, v
, tb
):
3390 setcontext(self
.saved_context
)
3392 class Context(object):
3393 """Contains the context for a Decimal instance.
3396 prec - precision (for use in rounding, division, square roots..)
3397 rounding - rounding type (how you round)
3398 traps - If traps[exception] = 1, then the exception is
3399 raised when it is caused. Otherwise, a value is
3401 flags - When an exception is caused, flags[exception] is incremented.
3402 (Whether or not the trap_enabler is set)
3403 Should be reset by user of Decimal instance.
3404 Emin - Minimum exponent
3405 Emax - Maximum exponent
3406 capitals - If 1, 1*10^1 is printed as 1E+1.
3407 If 0, printed as 1e1
3408 _clamp - If 1, change exponents if too high (Default 0)
3411 def __init__(self
, prec
=None, rounding
=None,
3412 traps
=None, flags
=None,
3413 Emin
=None, Emax
=None,
3414 capitals
=None, _clamp
=0,
3415 _ignored_flags
=None):
3418 if _ignored_flags
is None:
3420 if not isinstance(flags
, dict):
3421 flags
= dict([(s
,s
in flags
) for s
in _signals
])
3423 if traps
is not None and not isinstance(traps
, dict):
3424 traps
= dict([(s
,s
in traps
) for s
in _signals
])
3426 for name
, val
in locals().items():
3428 setattr(self
, name
, _copy
.copy(getattr(DefaultContext
, name
)))
3430 setattr(self
, name
, val
)
3434 """Show the current context."""
3436 s
.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3437 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3439 names
= [f
.__name
__ for f
, v
in self
.flags
.items() if v
]
3440 s
.append('flags=[' + ', '.join(names
) + ']')
3441 names
= [t
.__name
__ for t
, v
in self
.traps
.items() if v
]
3442 s
.append('traps=[' + ', '.join(names
) + ']')
3443 return ', '.join(s
) + ')'
3445 def clear_flags(self
):
3446 """Reset all flags to zero"""
3447 for flag
in self
.flags
:
3448 self
.flags
[flag
] = 0
3450 def _shallow_copy(self
):
3451 """Returns a shallow copy from self."""
3452 nc
= Context(self
.prec
, self
.rounding
, self
.traps
,
3453 self
.flags
, self
.Emin
, self
.Emax
,
3454 self
.capitals
, self
._clamp
, self
._ignored
_flags
)
3458 """Returns a deep copy from self."""
3459 nc
= Context(self
.prec
, self
.rounding
, self
.traps
.copy(),
3460 self
.flags
.copy(), self
.Emin
, self
.Emax
,
3461 self
.capitals
, self
._clamp
, self
._ignored
_flags
)
3465 def _raise_error(self
, condition
, explanation
= None, *args
):
3468 If the flag is in _ignored_flags, returns the default response.
3469 Otherwise, it increments the flag, then, if the corresponding
3470 trap_enabler is set, it reaises the exception. Otherwise, it returns
3471 the default value after incrementing the flag.
3473 error
= _condition_map
.get(condition
, condition
)
3474 if error
in self
._ignored
_flags
:
3475 # Don't touch the flag
3476 return error().handle(self
, *args
)
3478 self
.flags
[error
] += 1
3479 if not self
.traps
[error
]:
3480 # The errors define how to handle themselves.
3481 return condition().handle(self
, *args
)
3483 # Errors should only be risked on copies of the context
3484 # self._ignored_flags = []
3485 raise error
, explanation
3487 def _ignore_all_flags(self
):
3488 """Ignore all flags, if they are raised"""
3489 return self
._ignore
_flags
(*_signals
)
3491 def _ignore_flags(self
, *flags
):
3492 """Ignore the flags, if they are raised"""
3493 # Do not mutate-- This way, copies of a context leave the original
3495 self
._ignored
_flags
= (self
._ignored
_flags
+ list(flags
))
3498 def _regard_flags(self
, *flags
):
3499 """Stop ignoring the flags, if they are raised"""
3500 if flags
and isinstance(flags
[0], (tuple,list)):
3503 self
._ignored
_flags
.remove(flag
)
3506 """A Context cannot be hashed."""
3507 # We inherit object.__hash__, so we must deny this explicitly
3508 raise TypeError("Cannot hash a Context.")
3511 """Returns Etiny (= Emin - prec + 1)"""
3512 return int(self
.Emin
- self
.prec
+ 1)
3515 """Returns maximum exponent (= Emax - prec + 1)"""
3516 return int(self
.Emax
- self
.prec
+ 1)
3518 def _set_rounding(self
, type):
3519 """Sets the rounding type.
3521 Sets the rounding type, and returns the current (previous)
3522 rounding type. Often used like:
3524 context = context.copy()
3525 # so you don't change the calling context
3526 # if an error occurs in the middle.
3527 rounding = context._set_rounding(ROUND_UP)
3528 val = self.__sub__(other, context=context)
3529 context._set_rounding(rounding)
3531 This will make it round up for that operation.
3533 rounding
= self
.rounding
3537 def create_decimal(self
, num
='0'):
3538 """Creates a new Decimal instance but using self as context.
3540 This method implements the to-number operation of the
3541 IBM Decimal specification."""
3543 if isinstance(num
, basestring
) and num
!= num
.strip():
3544 return self
._raise
_error
(ConversionSyntax
,
3545 "no trailing or leading whitespace is "
3548 d
= Decimal(num
, context
=self
)
3549 if d
._isnan
() and len(d
._int
) > self
.prec
- self
._clamp
:
3550 return self
._raise
_error
(ConversionSyntax
,
3551 "diagnostic info too long in NaN")
3556 """Returns the absolute value of the operand.
3558 If the operand is negative, the result is the same as using the minus
3559 operation on the operand. Otherwise, the result is the same as using
3560 the plus operation on the operand.
3562 >>> ExtendedContext.abs(Decimal('2.1'))
3564 >>> ExtendedContext.abs(Decimal('-100'))
3566 >>> ExtendedContext.abs(Decimal('101.5'))
3568 >>> ExtendedContext.abs(Decimal('-101.5'))
3571 return a
.__abs
__(context
=self
)
3573 def add(self
, a
, b
):
3574 """Return the sum of the two operands.
3576 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3578 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3581 return a
.__add
__(b
, context
=self
)
3583 def _apply(self
, a
):
3584 return str(a
._fix
(self
))
3586 def canonical(self
, a
):
3587 """Returns the same Decimal object.
3589 As we do not have different encodings for the same number, the
3590 received object already is in its canonical form.
3592 >>> ExtendedContext.canonical(Decimal('2.50'))
3595 return a
.canonical(context
=self
)
3597 def compare(self
, a
, b
):
3598 """Compares values numerically.
3600 If the signs of the operands differ, a value representing each operand
3601 ('-1' if the operand is less than zero, '0' if the operand is zero or
3602 negative zero, or '1' if the operand is greater than zero) is used in
3603 place of that operand for the comparison instead of the actual
3606 The comparison is then effected by subtracting the second operand from
3607 the first and then returning a value according to the result of the
3608 subtraction: '-1' if the result is less than zero, '0' if the result is
3609 zero or negative zero, or '1' if the result is greater than zero.
3611 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3613 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3615 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3617 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3619 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3621 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3624 return a
.compare(b
, context
=self
)
3626 def compare_signal(self
, a
, b
):
3627 """Compares the values of the two operands numerically.
3629 It's pretty much like compare(), but all NaNs signal, with signaling
3630 NaNs taking precedence over quiet NaNs.
3632 >>> c = ExtendedContext
3633 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3635 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3637 >>> c.flags[InvalidOperation] = 0
3638 >>> print c.flags[InvalidOperation]
3640 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3642 >>> print c.flags[InvalidOperation]
3644 >>> c.flags[InvalidOperation] = 0
3645 >>> print c.flags[InvalidOperation]
3647 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3649 >>> print c.flags[InvalidOperation]
3652 return a
.compare_signal(b
, context
=self
)
3654 def compare_total(self
, a
, b
):
3655 """Compares two operands using their abstract representation.
3657 This is not like the standard compare, which use their numerical
3658 value. Note that a total ordering is defined for all possible abstract
3661 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3663 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3665 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3667 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3669 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3671 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3674 return a
.compare_total(b
)
3676 def compare_total_mag(self
, a
, b
):
3677 """Compares two operands using their abstract representation ignoring sign.
3679 Like compare_total, but with operand's sign ignored and assumed to be 0.
3681 return a
.compare_total_mag(b
)
3683 def copy_abs(self
, a
):
3684 """Returns a copy of the operand with the sign set to 0.
3686 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3688 >>> ExtendedContext.copy_abs(Decimal('-100'))
3693 def copy_decimal(self
, a
):
3694 """Returns a copy of the decimal objet.
3696 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3698 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3703 def copy_negate(self
, a
):
3704 """Returns a copy of the operand with the sign inverted.
3706 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3708 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3711 return a
.copy_negate()
3713 def copy_sign(self
, a
, b
):
3714 """Copies the second operand's sign to the first one.
3716 In detail, it returns a copy of the first operand with the sign
3717 equal to the sign of the second operand.
3719 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3721 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3723 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3725 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3728 return a
.copy_sign(b
)
3730 def divide(self
, a
, b
):
3731 """Decimal division in a specified context.
3733 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3734 Decimal("0.333333333")
3735 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3736 Decimal("0.666666667")
3737 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3739 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3741 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3743 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3745 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3747 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3749 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3751 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3754 return a
.__div
__(b
, context
=self
)
3756 def divide_int(self
, a
, b
):
3757 """Divides two numbers and returns the integer part of the result.
3759 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3761 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3763 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3766 return a
.__floordiv
__(b
, context
=self
)
3768 def divmod(self
, a
, b
):
3769 return a
.__divmod
__(b
, context
=self
)
3774 >>> c = ExtendedContext.copy()
3777 >>> c.exp(Decimal('-Infinity'))
3779 >>> c.exp(Decimal('-1'))
3780 Decimal("0.367879441")
3781 >>> c.exp(Decimal('0'))
3783 >>> c.exp(Decimal('1'))
3784 Decimal("2.71828183")
3785 >>> c.exp(Decimal('0.693147181'))
3786 Decimal("2.00000000")
3787 >>> c.exp(Decimal('+Infinity'))
3790 return a
.exp(context
=self
)
3792 def fma(self
, a
, b
, c
):
3793 """Returns a multiplied by b, plus c.
3795 The first two operands are multiplied together, using multiply,
3796 the third operand is then added to the result of that
3797 multiplication, using add, all with only one final rounding.
3799 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3801 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3803 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3804 Decimal("1.38435736E+12")
3806 return a
.fma(b
, c
, context
=self
)
3808 def is_canonical(self
, a
):
3809 """Return True if the operand is canonical; otherwise return False.
3811 Currently, the encoding of a Decimal instance is always
3812 canonical, so this method returns True for any Decimal.
3814 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3817 return a
.is_canonical()
3819 def is_finite(self
, a
):
3820 """Return True if the operand is finite; otherwise return False.
3822 A Decimal instance is considered finite if it is neither
3825 >>> ExtendedContext.is_finite(Decimal('2.50'))
3827 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3829 >>> ExtendedContext.is_finite(Decimal('0'))
3831 >>> ExtendedContext.is_finite(Decimal('Inf'))
3833 >>> ExtendedContext.is_finite(Decimal('NaN'))
3836 return a
.is_finite()
3838 def is_infinite(self
, a
):
3839 """Return True if the operand is infinite; otherwise return False.
3841 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3843 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3845 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3848 return a
.is_infinite()
3850 def is_nan(self
, a
):
3851 """Return True if the operand is a qNaN or sNaN;
3852 otherwise return False.
3854 >>> ExtendedContext.is_nan(Decimal('2.50'))
3856 >>> ExtendedContext.is_nan(Decimal('NaN'))
3858 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3863 def is_normal(self
, a
):
3864 """Return True if the operand is a normal number;
3865 otherwise return False.
3867 >>> c = ExtendedContext.copy()
3870 >>> c.is_normal(Decimal('2.50'))
3872 >>> c.is_normal(Decimal('0.1E-999'))
3874 >>> c.is_normal(Decimal('0.00'))
3876 >>> c.is_normal(Decimal('-Inf'))
3878 >>> c.is_normal(Decimal('NaN'))
3881 return a
.is_normal(context
=self
)
3883 def is_qnan(self
, a
):
3884 """Return True if the operand is a quiet NaN; otherwise return False.
3886 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3888 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3890 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3895 def is_signed(self
, a
):
3896 """Return True if the operand is negative; otherwise return False.
3898 >>> ExtendedContext.is_signed(Decimal('2.50'))
3900 >>> ExtendedContext.is_signed(Decimal('-12'))
3902 >>> ExtendedContext.is_signed(Decimal('-0'))
3905 return a
.is_signed()
3907 def is_snan(self
, a
):
3908 """Return True if the operand is a signaling NaN;
3909 otherwise return False.
3911 >>> ExtendedContext.is_snan(Decimal('2.50'))
3913 >>> ExtendedContext.is_snan(Decimal('NaN'))
3915 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3920 def is_subnormal(self
, a
):
3921 """Return True if the operand is subnormal; otherwise return False.
3923 >>> c = ExtendedContext.copy()
3926 >>> c.is_subnormal(Decimal('2.50'))
3928 >>> c.is_subnormal(Decimal('0.1E-999'))
3930 >>> c.is_subnormal(Decimal('0.00'))
3932 >>> c.is_subnormal(Decimal('-Inf'))
3934 >>> c.is_subnormal(Decimal('NaN'))
3937 return a
.is_subnormal(context
=self
)
3939 def is_zero(self
, a
):
3940 """Return True if the operand is a zero; otherwise return False.
3942 >>> ExtendedContext.is_zero(Decimal('0'))
3944 >>> ExtendedContext.is_zero(Decimal('2.50'))
3946 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3952 """Returns the natural (base e) logarithm of the operand.
3954 >>> c = ExtendedContext.copy()
3957 >>> c.ln(Decimal('0'))
3958 Decimal("-Infinity")
3959 >>> c.ln(Decimal('1.000'))
3961 >>> c.ln(Decimal('2.71828183'))
3962 Decimal("1.00000000")
3963 >>> c.ln(Decimal('10'))
3964 Decimal("2.30258509")
3965 >>> c.ln(Decimal('+Infinity'))
3968 return a
.ln(context
=self
)
3971 """Returns the base 10 logarithm of the operand.
3973 >>> c = ExtendedContext.copy()
3976 >>> c.log10(Decimal('0'))
3977 Decimal("-Infinity")
3978 >>> c.log10(Decimal('0.001'))
3980 >>> c.log10(Decimal('1.000'))
3982 >>> c.log10(Decimal('2'))
3983 Decimal("0.301029996")
3984 >>> c.log10(Decimal('10'))
3986 >>> c.log10(Decimal('70'))
3987 Decimal("1.84509804")
3988 >>> c.log10(Decimal('+Infinity'))
3991 return a
.log10(context
=self
)
3994 """ Returns the exponent of the magnitude of the operand's MSD.
3996 The result is the integer which is the exponent of the magnitude
3997 of the most significant digit of the operand (as though the
3998 operand were truncated to a single digit while maintaining the
3999 value of that digit and without limiting the resulting exponent).
4001 >>> ExtendedContext.logb(Decimal('250'))
4003 >>> ExtendedContext.logb(Decimal('2.50'))
4005 >>> ExtendedContext.logb(Decimal('0.03'))
4007 >>> ExtendedContext.logb(Decimal('0'))
4008 Decimal("-Infinity")
4010 return a
.logb(context
=self
)
4012 def logical_and(self
, a
, b
):
4013 """Applies the logical operation 'and' between each operand's digits.
4015 The operands must be both logical numbers.
4017 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4019 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4021 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4023 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4025 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4027 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4030 return a
.logical_and(b
, context
=self
)
4032 def logical_invert(self
, a
):
4033 """Invert all the digits in the operand.
4035 The operand must be a logical number.
4037 >>> ExtendedContext.logical_invert(Decimal('0'))
4038 Decimal("111111111")
4039 >>> ExtendedContext.logical_invert(Decimal('1'))
4040 Decimal("111111110")
4041 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4043 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4046 return a
.logical_invert(context
=self
)
4048 def logical_or(self
, a
, b
):
4049 """Applies the logical operation 'or' between each operand's digits.
4051 The operands must be both logical numbers.
4053 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4055 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4057 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4059 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4061 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4063 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4066 return a
.logical_or(b
, context
=self
)
4068 def logical_xor(self
, a
, b
):
4069 """Applies the logical operation 'xor' between each operand's digits.
4071 The operands must be both logical numbers.
4073 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4075 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4077 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4079 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4081 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4083 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4086 return a
.logical_xor(b
, context
=self
)
4089 """max compares two values numerically and returns the maximum.
4091 If either operand is a NaN then the general rules apply.
4092 Otherwise, the operands are compared as though by the compare
4093 operation. If they are numerically equal then the left-hand operand
4094 is chosen as the result. Otherwise the maximum (closer to positive
4095 infinity) of the two operands is chosen as the result.
4097 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4099 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4101 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4103 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4106 return a
.max(b
, context
=self
)
4108 def max_mag(self
, a
, b
):
4109 """Compares the values numerically with their sign ignored."""
4110 return a
.max_mag(b
, context
=self
)
4113 """min compares two values numerically and returns the minimum.
4115 If either operand is a NaN then the general rules apply.
4116 Otherwise, the operands are compared as though by the compare
4117 operation. If they are numerically equal then the left-hand operand
4118 is chosen as the result. Otherwise the minimum (closer to negative
4119 infinity) of the two operands is chosen as the result.
4121 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4123 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4125 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4127 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4130 return a
.min(b
, context
=self
)
4132 def min_mag(self
, a
, b
):
4133 """Compares the values numerically with their sign ignored."""
4134 return a
.min_mag(b
, context
=self
)
4137 """Minus corresponds to unary prefix minus in Python.
4139 The operation is evaluated using the same rules as subtract; the
4140 operation minus(a) is calculated as subtract('0', a) where the '0'
4141 has the same exponent as the operand.
4143 >>> ExtendedContext.minus(Decimal('1.3'))
4145 >>> ExtendedContext.minus(Decimal('-1.3'))
4148 return a
.__neg
__(context
=self
)
4150 def multiply(self
, a
, b
):
4151 """multiply multiplies two operands.
4153 If either operand is a special value then the general rules apply.
4154 Otherwise, the operands are multiplied together ('long multiplication'),
4155 resulting in a number which may be as long as the sum of the lengths
4156 of the two operands.
4158 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4160 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4162 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4164 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4166 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4167 Decimal("4.28135971E+11")
4169 return a
.__mul
__(b
, context
=self
)
4171 def next_minus(self
, a
):
4172 """Returns the largest representable number smaller than a.
4174 >>> c = ExtendedContext.copy()
4177 >>> ExtendedContext.next_minus(Decimal('1'))
4178 Decimal("0.999999999")
4179 >>> c.next_minus(Decimal('1E-1007'))
4181 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4182 Decimal("-1.00000004")
4183 >>> c.next_minus(Decimal('Infinity'))
4184 Decimal("9.99999999E+999")
4186 return a
.next_minus(context
=self
)
4188 def next_plus(self
, a
):
4189 """Returns the smallest representable number larger than a.
4191 >>> c = ExtendedContext.copy()
4194 >>> ExtendedContext.next_plus(Decimal('1'))
4195 Decimal("1.00000001")
4196 >>> c.next_plus(Decimal('-1E-1007'))
4198 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4199 Decimal("-1.00000002")
4200 >>> c.next_plus(Decimal('-Infinity'))
4201 Decimal("-9.99999999E+999")
4203 return a
.next_plus(context
=self
)
4205 def next_toward(self
, a
, b
):
4206 """Returns the number closest to a, in direction towards b.
4208 The result is the closest representable number from the first
4209 operand (but not the first operand) that is in the direction
4210 towards the second operand, unless the operands have the same
4213 >>> c = ExtendedContext.copy()
4216 >>> c.next_toward(Decimal('1'), Decimal('2'))
4217 Decimal("1.00000001")
4218 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4220 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4221 Decimal("-1.00000002")
4222 >>> c.next_toward(Decimal('1'), Decimal('0'))
4223 Decimal("0.999999999")
4224 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4226 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4227 Decimal("-1.00000004")
4228 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4231 return a
.next_toward(b
, context
=self
)
4233 def normalize(self
, a
):
4234 """normalize reduces an operand to its simplest form.
4236 Essentially a plus operation with all trailing zeros removed from the
4239 >>> ExtendedContext.normalize(Decimal('2.1'))
4241 >>> ExtendedContext.normalize(Decimal('-2.0'))
4243 >>> ExtendedContext.normalize(Decimal('1.200'))
4245 >>> ExtendedContext.normalize(Decimal('-120'))
4247 >>> ExtendedContext.normalize(Decimal('120.00'))
4249 >>> ExtendedContext.normalize(Decimal('0.00'))
4252 return a
.normalize(context
=self
)
4254 def number_class(self
, a
):
4255 """Returns an indication of the class of the operand.
4257 The class is one of the following strings:
4269 >>> c = Context(ExtendedContext)
4272 >>> c.number_class(Decimal('Infinity'))
4274 >>> c.number_class(Decimal('1E-10'))
4276 >>> c.number_class(Decimal('2.50'))
4278 >>> c.number_class(Decimal('0.1E-999'))
4280 >>> c.number_class(Decimal('0'))
4282 >>> c.number_class(Decimal('-0'))
4284 >>> c.number_class(Decimal('-0.1E-999'))
4286 >>> c.number_class(Decimal('-1E-10'))
4288 >>> c.number_class(Decimal('-2.50'))
4290 >>> c.number_class(Decimal('-Infinity'))
4292 >>> c.number_class(Decimal('NaN'))
4294 >>> c.number_class(Decimal('-NaN'))
4296 >>> c.number_class(Decimal('sNaN'))
4299 return a
.number_class(context
=self
)
4302 """Plus corresponds to unary prefix plus in Python.
4304 The operation is evaluated using the same rules as add; the
4305 operation plus(a) is calculated as add('0', a) where the '0'
4306 has the same exponent as the operand.
4308 >>> ExtendedContext.plus(Decimal('1.3'))
4310 >>> ExtendedContext.plus(Decimal('-1.3'))
4313 return a
.__pos
__(context
=self
)
4315 def power(self
, a
, b
, modulo
=None):
4316 """Raises a to the power of b, to modulo if given.
4318 With two arguments, compute a**b. If a is negative then b
4319 must be integral. The result will be inexact unless b is
4320 integral and the result is finite and can be expressed exactly
4321 in 'precision' digits.
4323 With three arguments, compute (a**b) % modulo. For the
4324 three argument form, the following restrictions on the
4327 - all three arguments must be integral
4328 - b must be nonnegative
4329 - at least one of a or b must be nonzero
4330 - modulo must be nonzero and have at most 'precision' digits
4332 The result of pow(a, b, modulo) is identical to the result
4333 that would be obtained by computing (a**b) % modulo with
4334 unbounded precision, but is computed more efficiently. It is
4337 >>> c = ExtendedContext.copy()
4340 >>> c.power(Decimal('2'), Decimal('3'))
4342 >>> c.power(Decimal('-2'), Decimal('3'))
4344 >>> c.power(Decimal('2'), Decimal('-3'))
4346 >>> c.power(Decimal('1.7'), Decimal('8'))
4347 Decimal("69.7575744")
4348 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4349 Decimal("2.00000000")
4350 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4352 >>> c.power(Decimal('Infinity'), Decimal('0'))
4354 >>> c.power(Decimal('Infinity'), Decimal('1'))
4356 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4358 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4360 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4361 Decimal("-Infinity")
4362 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4364 >>> c.power(Decimal('0'), Decimal('0'))
4367 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4369 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4371 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4373 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4375 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4377 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4379 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4382 return a
.__pow
__(b
, modulo
, context
=self
)
4384 def quantize(self
, a
, b
):
4385 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4387 The coefficient of the result is derived from that of the left-hand
4388 operand. It may be rounded using the current rounding setting (if the
4389 exponent is being increased), multiplied by a positive power of ten (if
4390 the exponent is being decreased), or is unchanged (if the exponent is
4391 already equal to that of the right-hand operand).
4393 Unlike other operations, if the length of the coefficient after the
4394 quantize operation would be greater than precision then an Invalid
4395 operation condition is raised. This guarantees that, unless there is
4396 an error condition, the exponent of the result of a quantize is always
4397 equal to that of the right-hand operand.
4399 Also unlike other operations, quantize will never raise Underflow, even
4400 if the result is subnormal and inexact.
4402 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4404 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4406 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4408 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4410 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4412 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4413 Decimal("-Infinity")
4414 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4416 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4418 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4420 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4422 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4424 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4426 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4428 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4430 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4433 return a
.quantize(b
, context
=self
)
4436 """Just returns 10, as this is Decimal, :)
4438 >>> ExtendedContext.radix()
4443 def remainder(self
, a
, b
):
4444 """Returns the remainder from integer division.
4446 The result is the residue of the dividend after the operation of
4447 calculating integer division as described for divide-integer, rounded
4448 to precision digits if necessary. The sign of the result, if
4449 non-zero, is the same as that of the original dividend.
4451 This operation will fail under the same conditions as integer division
4452 (that is, if integer division on the same two operands would fail, the
4453 remainder cannot be calculated).
4455 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4457 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4459 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4461 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4463 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4465 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4468 return a
.__mod
__(b
, context
=self
)
4470 def remainder_near(self
, a
, b
):
4471 """Returns to be "a - b * n", where n is the integer nearest the exact
4472 value of "x / b" (if two integers are equally near then the even one
4473 is chosen). If the result is equal to 0 then its sign will be the
4476 This operation will fail under the same conditions as integer division
4477 (that is, if integer division on the same two operands would fail, the
4478 remainder cannot be calculated).
4480 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4482 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4484 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4486 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4488 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4490 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4492 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4495 return a
.remainder_near(b
, context
=self
)
4497 def rotate(self
, a
, b
):
4498 """Returns a rotated copy of a, b times.
4500 The coefficient of the result is a rotated copy of the digits in
4501 the coefficient of the first operand. The number of places of
4502 rotation is taken from the absolute value of the second operand,
4503 with the rotation being to the left if the second operand is
4504 positive or to the right otherwise.
4506 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4507 Decimal("400000003")
4508 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4510 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4511 Decimal("891234567")
4512 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4513 Decimal("123456789")
4514 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4515 Decimal("345678912")
4517 return a
.rotate(b
, context
=self
)
4519 def same_quantum(self
, a
, b
):
4520 """Returns True if the two operands have the same exponent.
4522 The result is never affected by either the sign or the coefficient of
4525 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4527 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4529 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4531 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4534 return a
.same_quantum(b
)
4536 def scaleb (self
, a
, b
):
4537 """Returns the first operand after adding the second value its exp.
4539 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4541 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4543 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4546 return a
.scaleb (b
, context
=self
)
4548 def shift(self
, a
, b
):
4549 """Returns a shifted copy of a, b times.
4551 The coefficient of the result is a shifted copy of the digits
4552 in the coefficient of the first operand. The number of places
4553 to shift is taken from the absolute value of the second operand,
4554 with the shift being to the left if the second operand is
4555 positive or to the right otherwise. Digits shifted into the
4556 coefficient are zeros.
4558 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4559 Decimal("400000000")
4560 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4562 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4564 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4565 Decimal("123456789")
4566 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4567 Decimal("345678900")
4569 return a
.shift(b
, context
=self
)
4572 """Square root of a non-negative number to context precision.
4574 If the result must be inexact, it is rounded using the round-half-even
4577 >>> ExtendedContext.sqrt(Decimal('0'))
4579 >>> ExtendedContext.sqrt(Decimal('-0'))
4581 >>> ExtendedContext.sqrt(Decimal('0.39'))
4582 Decimal("0.624499800")
4583 >>> ExtendedContext.sqrt(Decimal('100'))
4585 >>> ExtendedContext.sqrt(Decimal('1'))
4587 >>> ExtendedContext.sqrt(Decimal('1.0'))
4589 >>> ExtendedContext.sqrt(Decimal('1.00'))
4591 >>> ExtendedContext.sqrt(Decimal('7'))
4592 Decimal("2.64575131")
4593 >>> ExtendedContext.sqrt(Decimal('10'))
4594 Decimal("3.16227766")
4595 >>> ExtendedContext.prec
4598 return a
.sqrt(context
=self
)
4600 def subtract(self
, a
, b
):
4601 """Return the difference between the two operands.
4603 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4605 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4607 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4610 return a
.__sub
__(b
, context
=self
)
4612 def to_eng_string(self
, a
):
4613 """Converts a number to a string, using scientific notation.
4615 The operation is not affected by the context.
4617 return a
.to_eng_string(context
=self
)
4619 def to_sci_string(self
, a
):
4620 """Converts a number to a string, using scientific notation.
4622 The operation is not affected by the context.
4624 return a
.__str
__(context
=self
)
4626 def to_integral_exact(self
, a
):
4627 """Rounds to an integer.
4629 When the operand has a negative exponent, the result is the same
4630 as using the quantize() operation using the given operand as the
4631 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4632 of the operand as the precision setting; Inexact and Rounded flags
4633 are allowed in this operation. The rounding mode is taken from the
4636 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4638 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4640 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4642 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4644 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4646 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4648 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4650 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4651 Decimal("-Infinity")
4653 return a
.to_integral_exact(context
=self
)
4655 def to_integral_value(self
, a
):
4656 """Rounds to an integer.
4658 When the operand has a negative exponent, the result is the same
4659 as using the quantize() operation using the given operand as the
4660 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4661 of the operand as the precision setting, except that no flags will
4662 be set. The rounding mode is taken from the context.
4664 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4666 >>> ExtendedContext.to_integral_value(Decimal('100'))
4668 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4670 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4672 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4674 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4676 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4678 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4679 Decimal("-Infinity")
4681 return a
.to_integral_value(context
=self
)
4683 # the method name changed, but we provide also the old one, for compatibility
4684 to_integral
= to_integral_value
4686 class _WorkRep(object):
4687 __slots__
= ('sign','int','exp')
4690 # exp: None, int, or string
4692 def __init__(self
, value
=None):
4697 elif isinstance(value
, Decimal
):
4698 self
.sign
= value
._sign
4699 self
.int = int(value
._int
)
4700 self
.exp
= value
._exp
4702 # assert isinstance(value, tuple)
4703 self
.sign
= value
[0]
4708 return "(%r, %r, %r)" % (self
.sign
, self
.int, self
.exp
)
4714 def _normalize(op1
, op2
, prec
= 0):
4715 """Normalizes op1, op2 to have the same exp and length of coefficient.
4717 Done during addition.
4719 if op1
.exp
< op2
.exp
:
4726 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4727 # Then adding 10**exp to tmp has the same effect (after rounding)
4728 # as adding any positive quantity smaller than 10**exp; similarly
4729 # for subtraction. So if other is smaller than 10**exp we replace
4730 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4731 tmp_len
= len(str(tmp
.int))
4732 other_len
= len(str(other
.int))
4733 exp
= tmp
.exp
+ min(-1, tmp_len
- prec
- 2)
4734 if other_len
+ other
.exp
- 1 < exp
:
4738 tmp
.int *= 10 ** (tmp
.exp
- other
.exp
)
4742 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4744 # This function from Tim Peters was taken from here:
4745 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4746 # The correction being in the function definition is for speed, and
4747 # the whole function is not resolved with math.log because of avoiding
4748 # the use of floats.
4749 def _nbits(n
, correction
= {
4750 '0': 4, '1': 3, '2': 2, '3': 2,
4751 '4': 1, '5': 1, '6': 1, '7': 1,
4752 '8': 0, '9': 0, 'a': 0, 'b': 0,
4753 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4754 """Number of bits in binary representation of the positive integer n,
4758 raise ValueError("The argument to _nbits should be nonnegative.")
4760 return 4*len(hex_n
) - correction
[hex_n
[0]]
4762 def _sqrt_nearest(n
, a
):
4763 """Closest integer to the square root of the positive integer n. a is
4764 an initial approximation to the square root. Any positive integer
4765 will do for a, but the closer a is to the square root of n the
4766 faster convergence will be.
4769 if n
<= 0 or a
<= 0:
4770 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4774 b
, a
= a
, a
--n
//a
>>1
4777 def _rshift_nearest(x
, shift
):
4778 """Given an integer x and a nonnegative integer shift, return closest
4779 integer to x / 2**shift; use round-to-even in case of a tie.
4782 b
, q
= 1L << shift
, x
>> shift
4783 return q
+ (2*(x
& (b
-1)) + (q
&1) > b
)
4785 def _div_nearest(a
, b
):
4786 """Closest integer to a/b, a and b positive integers; rounds to even
4787 in the case of a tie.
4791 return q
+ (2*r
+ (q
&1) > b
)
4793 def _ilog(x
, M
, L
= 8):
4794 """Integer approximation to M*log(x/M), with absolute error boundable
4795 in terms only of x/M.
4797 Given positive integers x and M, return an integer approximation to
4798 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4799 between the approximation and the exact result is at most 22. For
4800 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4801 both cases these are upper bounds on the error; it will usually be
4804 # The basic algorithm is the following: let log1p be the function
4805 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4808 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4810 # repeatedly until the argument to log1p is small (< 2**-L in
4811 # absolute value). For small y we can use the Taylor series
4814 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4816 # truncating at T such that y**T is small enough. The whole
4817 # computation is carried out in a form of fixed-point arithmetic,
4818 # with a real number z being represented by an integer
4819 # approximation to z*M. To avoid loss of precision, the y below
4820 # is actually an integer approximation to 2**R*y*M, where R is the
4821 # number of reductions performed so far.
4824 # argument reduction; R = number of reductions performed
4826 while (R
<= L
and long(abs(y
)) << L
-R
>= M
or
4827 R
> L
and abs(y
) >> R
-L
>= M
):
4828 y
= _div_nearest(long(M
*y
) << 1,
4829 M
+ _sqrt_nearest(M
*(M
+_rshift_nearest(y
, R
)), M
))
4832 # Taylor series with T terms
4833 T
= -int(-10*len(str(M
))//(3*L
))
4834 yshift
= _rshift_nearest(y
, R
)
4835 w
= _div_nearest(M
, T
)
4836 for k
in xrange(T
-1, 0, -1):
4837 w
= _div_nearest(M
, k
) - _div_nearest(yshift
*w
, M
)
4839 return _div_nearest(w
*y
, M
)
4841 def _dlog10(c
, e
, p
):
4842 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4843 approximation to 10**p * log10(c*10**e), with an absolute error of
4844 at most 1. Assumes that c*10**e is not exactly 1."""
4846 # increase precision by 2; compensate for this by dividing
4847 # final result by 100
4850 # write c*10**e as d*10**f with either:
4851 # f >= 0 and 1 <= d <= 10, or
4852 # f <= 0 and 0.1 <= d <= 1.
4853 # Thus for c*10**e close to 1, f = 0
4855 f
= e
+l
- (e
+l
>= 1)
4863 c
= _div_nearest(c
, 10**-k
)
4865 log_d
= _ilog(c
, M
) # error < 5 + 22 = 27
4866 log_10
= _log10_digits(p
) # error < 1
4867 log_d
= _div_nearest(log_d
*M
, log_10
)
4868 log_tenpower
= f
*M
# exact
4870 log_d
= 0 # error < 2.31
4871 log_tenpower
= div_nearest(f
, 10**-p
) # error < 0.5
4873 return _div_nearest(log_tenpower
+log_d
, 100)
4876 """Given integers c, e and p with c > 0, compute an integer
4877 approximation to 10**p * log(c*10**e), with an absolute error of
4878 at most 1. Assumes that c*10**e is not exactly 1."""
4880 # Increase precision by 2. The precision increase is compensated
4881 # for at the end with a division by 100.
4884 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4885 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4886 # as 10**p * log(d) + 10**p*f * log(10).
4888 f
= e
+l
- (e
+l
>= 1)
4890 # compute approximation to 10**p*log(d), with error < 27
4896 c
= _div_nearest(c
, 10**-k
) # error of <= 0.5 in c
4898 # _ilog magnifies existing error in c by a factor of at most 10
4899 log_d
= _ilog(c
, 10**p
) # error < 5 + 22 = 27
4901 # p <= 0: just approximate the whole thing by 0; error < 2.31
4904 # compute approximation to f*10**p*log(10), with error < 11.
4906 extra
= len(str(abs(f
)))-1
4908 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4909 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4910 f_log_ten
= _div_nearest(f
*_log10_digits(p
+extra
), 10**extra
)
4916 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4917 return _div_nearest(f_log_ten
+ log_d
, 100)
4919 class _Log10Memoize(object):
4920 """Class to compute, store, and allow retrieval of, digits of the
4921 constant log(10) = 2.302585.... This constant is needed by
4922 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4924 self
.digits
= "23025850929940456840179914546843642076011014886"
4926 def getdigits(self
, p
):
4927 """Given an integer p >= 0, return floor(10**p)*log(10).
4929 For example, self.getdigits(3) returns 2302.
4931 # digits are stored as a string, for quick conversion to
4932 # integer in the case that we've already computed enough
4933 # digits; the stored digits should always be correct
4934 # (truncated, not rounded to nearest).
4936 raise ValueError("p should be nonnegative")
4938 if p
>= len(self
.digits
):
4939 # compute p+3, p+6, p+9, ... digits; continue until at
4940 # least one of the extra digits is nonzero
4943 # compute p+extra digits, correct to within 1ulp
4945 digits
= str(_div_nearest(_ilog(10*M
, M
), 100))
4946 if digits
[-extra
:] != '0'*extra
:
4949 # keep all reliable digits so far; remove trailing zeros
4950 # and next nonzero digit
4951 self
.digits
= digits
.rstrip('0')[:-1]
4952 return int(self
.digits
[:p
+1])
4954 _log10_digits
= _Log10Memoize().getdigits
4956 def _iexp(x
, M
, L
=8):
4957 """Given integers x and M, M > 0, such that x/M is small in absolute
4958 value, compute an integer approximation to M*exp(x/M). For 0 <=
4959 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4960 is usually much smaller)."""
4962 # Algorithm: to compute exp(z) for a real number z, first divide z
4963 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4964 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4967 # expm1(x) = x + x**2/2! + x**3/3! + ...
4969 # Now use the identity
4971 # expm1(2x) = expm1(x)*(expm1(x)+2)
4973 # R times to compute the sequence expm1(z/2**R),
4974 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4976 # Find R such that x/2**R/M <= 2**-L
4977 R
= _nbits((long(x
)<<L
)//M
)
4979 # Taylor series. (2**L)**T > M
4980 T
= -int(-10*len(str(M
))//(3*L
))
4981 y
= _div_nearest(x
, T
)
4983 for i
in xrange(T
-1, 0, -1):
4984 y
= _div_nearest(x
*(Mshift
+ y
), Mshift
* i
)
4987 for k
in xrange(R
-1, -1, -1):
4988 Mshift
= long(M
)<<(k
+2)
4989 y
= _div_nearest(y
*(y
+Mshift
), Mshift
)
4994 """Compute an approximation to exp(c*10**e), with p decimal places of
4997 Returns integers d, f such that:
4999 10**(p-1) <= d <= 10**p, and
5000 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5002 In other words, d*10**f is an approximation to exp(c*10**e) with p
5003 digits of precision, and with an error in d of at most 1. This is
5004 almost, but not quite, the same as the error being < 1ulp: when d
5005 = 10**(p-1) the error could be up to 10 ulp."""
5007 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5010 # compute log(10) with extra precision = adjusted exponent of c*10**e
5011 extra
= max(0, e
+ len(str(c
)) - 1)
5014 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5018 cshift
= c
*10**shift
5020 cshift
= c
//10**-shift
5021 quot
, rem
= divmod(cshift
, _log10_digits(q
))
5023 # reduce remainder back to original precision
5024 rem
= _div_nearest(rem
, 10**extra
)
5026 # error in result of _iexp < 120; error after division < 0.62
5027 return _div_nearest(_iexp(rem
, 10**p
), 1000), quot
- p
+ 3
5029 def _dpower(xc
, xe
, yc
, ye
, p
):
5030 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5031 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5033 10**(p-1) <= c <= 10**p, and
5034 (c-1)*10**e < x**y < (c+1)*10**e
5036 in other words, c*10**e is an approximation to x**y with p digits
5037 of precision, and with an error in c of at most 1. (This is
5038 almost, but not quite, the same as the error being < 1ulp: when c
5039 == 10**(p-1) we can only guarantee error < 10ulp.)
5041 We assume that: x is positive and not equal to 1, and y is nonzero.
5044 # Find b such that 10**(b-1) <= |y| <= 10**b
5045 b
= len(str(abs(yc
))) + ye
5047 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5048 lxc
= _dlog(xc
, xe
, p
+b
+1)
5050 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5053 pc
= lxc
*yc
*10**shift
5055 pc
= _div_nearest(lxc
*yc
, 10**-shift
)
5058 # we prefer a result that isn't exactly 1; this makes it
5059 # easier to compute a correctly rounded result in __pow__
5060 if ((len(str(xc
)) + xe
>= 1) == (yc
> 0)): # if x**y > 1:
5061 coeff
, exp
= 10**(p
-1)+1, 1-p
5063 coeff
, exp
= 10**p
-1, -p
5065 coeff
, exp
= _dexp(pc
, -(p
+1), p
+1)
5066 coeff
= _div_nearest(coeff
, 10)
5071 def _log10_lb(c
, correction
= {
5072 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5073 '6': 23, '7': 16, '8': 10, '9': 5}):
5074 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5076 raise ValueError("The argument to _log10_lb should be nonnegative.")
5078 return 100*len(str_c
) - correction
[str_c
[0]]
5080 ##### Helper Functions ####################################################
5082 def _convert_other(other
, raiseit
=False):
5083 """Convert other to Decimal.
5085 Verifies that it's ok to use in an implicit construction.
5087 if isinstance(other
, Decimal
):
5089 if isinstance(other
, (int, long)):
5090 return Decimal(other
)
5092 raise TypeError("Unable to convert %s to Decimal" % other
)
5093 return NotImplemented
5095 ##### Setup Specific Contexts ############################################
5097 # The default context prototype used by Context()
5098 # Is mutable, so that new contexts can have different default values
5100 DefaultContext
= Context(
5101 prec
=28, rounding
=ROUND_HALF_EVEN
,
5102 traps
=[DivisionByZero
, Overflow
, InvalidOperation
],
5109 # Pre-made alternate contexts offered by the specification
5110 # Don't change these; the user should be able to select these
5111 # contexts and be able to reproduce results from other implementations
5114 BasicContext
= Context(
5115 prec
=9, rounding
=ROUND_HALF_UP
,
5116 traps
=[DivisionByZero
, Overflow
, InvalidOperation
, Clamped
, Underflow
],
5120 ExtendedContext
= Context(
5121 prec
=9, rounding
=ROUND_HALF_EVEN
,
5127 ##### crud for parsing strings #############################################
5130 # Regular expression used for parsing numeric strings. Additional
5133 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5134 # whitespace. But note that the specification disallows whitespace in
5137 # 2. For finite numbers (not infinities and NaNs) the body of the
5138 # number between the optional sign and the optional exponent must have
5139 # at least one decimal digit, possibly after the decimal point. The
5140 # lookahead expression '(?=\d|\.\d)' checks this.
5142 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5143 # other meaning for \d than the numbers [0-9].
5146 _parser
= re
.compile(r
""" # A numeric string consists of:
5148 (?P<sign>[-+])? # an optional sign, followed by either...
5150 (?=\d|\.\d) # ...a number (with at least one digit)
5151 (?P<int>\d*) # consisting of a (possibly empty) integer part
5152 (\.(?P<frac>\d*))? # followed by an optional fractional part
5153 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5155 Inf(inity)? # ...an infinity, or...
5157 (?P<signal>s)? # ...an (optionally signaling)
5159 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5163 """, re
.VERBOSE | re
.IGNORECASE
).match
5165 _all_zeros
= re
.compile('0*$').match
5166 _exact_half
= re
.compile('50*$').match
5170 ##### Useful Constants (internal use only) ################################
5173 Inf
= Decimal('Inf')
5174 negInf
= Decimal('-Inf')
5175 NaN
= Decimal('NaN')
5178 Dec_n1
= Decimal(-1)
5180 # Infsign[sign] is infinity w/ that sign
5181 Infsign
= (Inf
, negInf
)
5185 if __name__
== '__main__':
5187 doctest
.testmod(sys
.modules
[__name__
])