1 # -*- encoding: utf-8 -*-
2 # Copyright (c) 2004 Python Software Foundation.
5 # Written by Eric Price <eprice at tjhsst.edu>
6 # and Facundo Batista <facundo at taniquetil.com.ar>
7 # and Raymond Hettinger <python at rcn.com>
8 # and Aahz <aahz at pobox.com>
11 # This module is currently Py2.3 compatible and should be kept that way
12 # unless a major compelling advantage arises. IOW, 2.3 compatibility is
13 # strongly preferred, but not guaranteed.
15 # Also, this module should be kept in sync with the latest updates of
16 # the IBM specification as it evolves. Those updates will be treated
17 # as bug fixes (deviation from the spec is a compatibility, usability
18 # bug) and will be backported. At this point the spec is stabilizing
19 # and the updates are becoming fewer, smaller, and less significant.
22 This is a Py2.3 implementation of decimal floating point arithmetic based on
23 the General Decimal Arithmetic Specification:
25 www2.hursley.ibm.com/decimal/decarith.html
27 and IEEE standard 854-1987:
29 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
31 Decimal floating point has finite precision with arbitrarily large bounds.
33 The purpose of the module is to support arithmetic using familiar
34 "schoolhouse" rules and to avoid the some of tricky representation
35 issues associated with binary floating point. The package is especially
36 useful for financial applications or for contexts where users have
37 expectations that are at odds with binary floating point (for instance,
38 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
39 of the expected Decimal("0.00") returned by decimal floating point).
41 Here are some examples of using the decimal module:
43 >>> from decimal import *
44 >>> setcontext(ExtendedContext)
53 >>> Decimal("123.45e12345678901234567890")
54 Decimal("1.2345E+12345678901234567892")
55 >>> Decimal("1.33") + Decimal("1.27")
57 >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
60 >>> print dig / Decimal(3)
62 >>> getcontext().prec = 18
63 >>> print dig / Decimal(3)
67 >>> print Decimal(3).sqrt()
69 >>> print Decimal(3) ** 123
70 4.85192780976896427E+58
71 >>> inf = Decimal(1) / Decimal(0)
74 >>> neginf = Decimal(-1) / Decimal(0)
77 >>> print neginf + inf
79 >>> print neginf * inf
83 >>> getcontext().traps[DivisionByZero] = 1
85 Traceback (most recent call last):
91 >>> c.traps[InvalidOperation] = 0
92 >>> print c.flags[InvalidOperation]
94 >>> c.divide(Decimal(0), Decimal(0))
96 >>> c.traps[InvalidOperation] = 1
97 >>> print c.flags[InvalidOperation]
99 >>> c.flags[InvalidOperation] = 0
100 >>> print c.flags[InvalidOperation]
102 >>> print c.divide(Decimal(0), Decimal(0))
103 Traceback (most recent call last):
107 InvalidOperation: 0 / 0
108 >>> print c.flags[InvalidOperation]
110 >>> c.flags[InvalidOperation] = 0
111 >>> c.traps[InvalidOperation] = 0
112 >>> print c.divide(Decimal(0), Decimal(0))
114 >>> print c.flags[InvalidOperation]
121 'Decimal', 'Context',
124 'DefaultContext', 'BasicContext', 'ExtendedContext',
127 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
128 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
130 # Constants for use in setting up contexts
131 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
132 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN',
134 # Functions for manipulating contexts
135 'setcontext', 'getcontext'
141 ROUND_DOWN = 'ROUND_DOWN'
142 ROUND_HALF_UP = 'ROUND_HALF_UP'
143 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
144 ROUND_CEILING = 'ROUND_CEILING'
145 ROUND_FLOOR = 'ROUND_FLOOR'
146 ROUND_UP = 'ROUND_UP'
147 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
149 #Rounding decision (not part of the public API)
150 NEVER_ROUND = 'NEVER_ROUND' # Round in division (non-divmod), sqrt ONLY
151 ALWAYS_ROUND = 'ALWAYS_ROUND' # Every operation rounds at end.
155 class DecimalException(ArithmeticError):
156 """Base exception class.
158 Used exceptions derive from this.
159 If an exception derives from another exception besides this (such as
160 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
161 called if the others are present. This isn't actually used for
164 handle -- Called when context._raise_error is called and the
165 trap_enabler is set. First argument is self, second is the
166 context. More arguments can be given, those being after
167 the explanation in _raise_error (For example,
168 context._raise_error(NewError, '(-x)!', self._sign) would
169 call NewError().handle(context, self._sign).)
171 To define a new exception, it should be sufficient to have it derive
172 from DecimalException.
174 def handle(self, context, *args):
178 class Clamped(DecimalException):
179 """Exponent of a 0 changed to fit bounds.
181 This occurs and signals clamped if the exponent of a result has been
182 altered in order to fit the constraints of a specific concrete
183 representation. This may occur when the exponent of a zero result would
184 be outside the bounds of a representation, or when a large normal
185 number would have an encoded exponent that cannot be represented. In
186 this latter case, the exponent is reduced to fit and the corresponding
187 number of zero digits are appended to the coefficient ("fold-down").
191 class InvalidOperation(DecimalException):
192 """An invalid operation was performed.
194 Various bad things cause this:
196 Something creates a signaling NaN
202 x._rescale( non-integer )
207 An operand is invalid
209 def handle(self, context, *args):
211 if args[0] == 1: #sNaN, must drop 's' but keep diagnostics
212 return Decimal( (args[1]._sign, args[1]._int, 'n') )
215 class ConversionSyntax(InvalidOperation):
216 """Trying to convert badly formed string.
218 This occurs and signals invalid-operation if an string is being
219 converted to a number and it does not conform to the numeric string
220 syntax. The result is [0,qNaN].
223 def handle(self, context, *args):
224 return (0, (0,), 'n') #Passed to something which uses a tuple.
226 class DivisionByZero(DecimalException, ZeroDivisionError):
229 This occurs and signals division-by-zero if division of a finite number
230 by zero was attempted (during a divide-integer or divide operation, or a
231 power operation with negative right-hand operand), and the dividend was
234 The result of the operation is [sign,inf], where sign is the exclusive
235 or of the signs of the operands for divide, or is 1 for an odd power of
239 def handle(self, context, sign, double = None, *args):
240 if double is not None:
241 return (Infsign[sign],)*2
244 class DivisionImpossible(InvalidOperation):
245 """Cannot perform the division adequately.
247 This occurs and signals invalid-operation if the integer result of a
248 divide-integer or remainder operation had too many digits (would be
249 longer than precision). The result is [0,qNaN].
252 def handle(self, context, *args):
255 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
256 """Undefined result of division.
258 This occurs and signals invalid-operation if division by zero was
259 attempted (during a divide-integer, divide, or remainder operation), and
260 the dividend is also zero. The result is [0,qNaN].
263 def handle(self, context, tup=None, *args):
265 return (NaN, NaN) #for 0 %0, 0 // 0
268 class Inexact(DecimalException):
269 """Had to round, losing information.
271 This occurs and signals inexact whenever the result of an operation is
272 not exact (that is, it needed to be rounded and any discarded digits
273 were non-zero), or if an overflow or underflow condition occurs. The
274 result in all cases is unchanged.
276 The inexact signal may be tested (or trapped) to determine if a given
277 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.
308 class Subnormal(DecimalException):
309 """Exponent < Emin before rounding.
311 This occurs and signals subnormal whenever the result of a conversion or
312 operation is subnormal (that is, its adjusted exponent is less than
313 Emin, before any rounding). The result in all cases is unchanged.
315 The subnormal signal may be tested (or trapped) to determine if a given
316 or operation (or sequence of operations) yielded a subnormal result.
320 class Overflow(Inexact, Rounded):
321 """Numerical overflow.
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
328 The result depends on the rounding mode:
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
332 where sign is the sign of the intermediate result. For round-down, the
333 result is the largest finite number that can be represented in the
334 current precision, with the sign of the intermediate result. For
335 round-ceiling, the result is the same as for round-down if the sign of
336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
337 the result is the same as for round-down if the sign of the intermediate
338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
344 ROUND_HALF_DOWN, ROUND_UP):
347 if context.rounding == ROUND_CEILING:
349 return Decimal((sign, (9,)*context.prec,
350 context.Emax-context.prec+1))
352 if context.rounding == ROUND_FLOOR:
354 return Decimal( (sign, (9,)*context.prec,
355 context.Emax-context.prec+1))
358 class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
364 Emin). That is, the result is both inexact and subnormal.
366 The result after an underflow will be a subnormal number rounded, if
367 necessary, so that its exponent is not less than Etiny. This may result
368 in 0 with the sign of the intermediate result and an exponent of Etiny.
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
373 # List of public traps and flags
374 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
375 Underflow, InvalidOperation, Subnormal]
377 # Map conditions (per the spec) to signals
378 _condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
383 ##### Context Functions #######################################
385 # The getcontext() and setcontext() function manage access to a thread-local
386 # current context. Py2.4 offers direct support for thread locals. If that
387 # is not available, use threading.currentThread() which is slower but will
388 # work for older Pythons. If threads are not part of the build, create a
389 # mock threading object with threading.local() returning the module namespace.
394 # Python was compiled without threads; create a mock object instead
397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
405 except AttributeError:
407 #To fix reloading, force it to create a new context
408 #Old contexts have different exceptions in their dicts, making problems.
409 if hasattr(threading.currentThread(), '__decimal_context__'):
410 del threading.currentThread().__decimal_context__
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
415 context = context.copy()
416 context.clear_flags()
417 threading.currentThread().__decimal_context__ = context
420 """Returns this thread's context.
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
427 return threading.currentThread().__decimal_context__
428 except AttributeError:
430 threading.currentThread().__decimal_context__ = context
435 local = threading.local()
436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
439 def getcontext(_local=local):
440 """Returns this thread's context.
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
447 return _local.__decimal_context__
448 except AttributeError:
450 _local.__decimal_context__ = context
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
456 context = context.copy()
457 context.clear_flags()
458 _local.__decimal_context__ = context
460 del threading, local # Don't contaminate the namespace
463 ##### Decimal class ###########################################
465 class Decimal(object):
466 """Floating point class for decimal arithmetic."""
468 __slots__ = ('_exp','_int','_sign', '_is_special')
469 # Generally, the value of the Decimal instance is given by
470 # (-1)**_sign * _int * 10**_exp
471 # Special values are signified by _is_special == True
473 # We're immutable, so use __new__ not __init__
474 def __new__(cls, value="0", context=None):
475 """Create a decimal point instance.
477 >>> Decimal('3.14') # string input
479 >>> Decimal((0, (3, 1, 4), -2)) # tuple input (sign, digit_tuple, exponent)
481 >>> Decimal(314) # int or long
483 >>> Decimal(Decimal(314)) # another decimal instance
487 self = object.__new__(cls)
488 self._is_special = False
490 # From an internal working value
491 if isinstance(value, _WorkRep):
492 self._sign = value.sign
493 self._int = tuple(map(int, str(value.int)))
494 self._exp = int(value.exp)
497 # From another decimal
498 if isinstance(value, Decimal):
499 self._exp = value._exp
500 self._sign = value._sign
501 self._int = value._int
502 self._is_special = value._is_special
506 if isinstance(value, (int,long)):
512 self._int = tuple(map(int, str(abs(value))))
515 # tuple/list conversion (possibly from as_tuple())
516 if isinstance(value, (list,tuple)):
518 raise ValueError, 'Invalid arguments'
519 if value[0] not in (0,1):
520 raise ValueError, 'Invalid sign'
521 for digit in value[1]:
522 if not isinstance(digit, (int,long)) or digit < 0:
523 raise ValueError, "The second value in the tuple must be composed of non negative integer elements."
525 self._sign = value[0]
526 self._int = tuple(value[1])
527 if value[2] in ('F','n','N'):
529 self._is_special = True
531 self._exp = int(value[2])
534 if isinstance(value, float):
535 raise TypeError("Cannot convert float to Decimal. " +
536 "First convert the float to a string")
538 # Other argument types may require the context during interpretation
540 context = getcontext()
543 # REs insist on real strings, so we can too.
544 if isinstance(value, basestring):
545 if _isinfinity(value):
548 self._is_special = True
549 if _isinfinity(value) == 1:
555 sig, sign, diag = _isnan(value)
556 self._is_special = True
557 if len(diag) > context.prec: #Diagnostic info too long
558 self._sign, self._int, self._exp = \
559 context._raise_error(ConversionSyntax)
562 self._exp = 'n' #qNaN
564 self._exp = 'N' #sNaN
566 self._int = tuple(map(int, diag)) #Diagnostic info
569 self._sign, self._int, self._exp = _string2exact(value)
571 self._is_special = True
572 self._sign, self._int, self._exp = context._raise_error(ConversionSyntax)
575 raise TypeError("Cannot convert %r to Decimal" % value)
578 """Returns whether the number is not actually one.
592 def _isinfinity(self):
593 """Returns whether the number is infinite
595 0 if finite or not a number
605 def _check_nans(self, other = None, context=None):
606 """Returns whether the number is not actually one.
608 if self, other are sNaN, signal
609 if self, other are NaN return nan
612 Done before operations.
615 self_is_nan = self._isnan()
619 other_is_nan = other._isnan()
621 if self_is_nan or other_is_nan:
623 context = getcontext()
626 return context._raise_error(InvalidOperation, 'sNaN',
628 if other_is_nan == 2:
629 return context._raise_error(InvalidOperation, 'sNaN',
637 def __nonzero__(self):
638 """Is the number non-zero?
645 return sum(self._int) != 0
647 def __cmp__(self, other, context=None):
648 other = _convert_other(other)
649 if other is NotImplemented:
652 if self._is_special or other._is_special:
653 ans = self._check_nans(other, context)
655 return 1 # Comparison involving NaN's always reports self > other
658 return cmp(self._isinfinity(), other._isinfinity())
660 if not self and not other:
661 return 0 #If both 0, sign comparison isn't certain.
663 #If different signs, neg one is less
664 if other._sign < self._sign:
666 if self._sign < other._sign:
669 self_adjusted = self.adjusted()
670 other_adjusted = other.adjusted()
671 if self_adjusted == other_adjusted and \
672 self._int + (0,)*(self._exp - other._exp) == \
673 other._int + (0,)*(other._exp - self._exp):
674 return 0 #equal, except in precision. ([0]*(-x) = [])
675 elif self_adjusted > other_adjusted and self._int[0] != 0:
676 return (-1)**self._sign
677 elif self_adjusted < other_adjusted and other._int[0] != 0:
678 return -((-1)**self._sign)
680 # Need to round, so make sure we have a valid context
682 context = getcontext()
684 context = context._shallow_copy()
685 rounding = context._set_rounding(ROUND_UP) #round away from 0
687 flags = context._ignore_all_flags()
688 res = self.__sub__(other, context=context)
690 context._regard_flags(*flags)
692 context.rounding = rounding
700 def __eq__(self, other):
701 if not isinstance(other, (Decimal, int, long)):
702 return NotImplemented
703 return self.__cmp__(other) == 0
705 def __ne__(self, other):
706 if not isinstance(other, (Decimal, int, long)):
707 return NotImplemented
708 return self.__cmp__(other) != 0
710 def compare(self, other, context=None):
711 """Compares one to another.
717 Like __cmp__, but returns Decimal instances.
719 other = _convert_other(other)
720 if other is NotImplemented:
723 #compare(NaN, NaN) = NaN
724 if (self._is_special or other and other._is_special):
725 ans = self._check_nans(other, context)
729 return Decimal(self.__cmp__(other, context))
732 """x.__hash__() <==> hash(x)"""
733 # Decimal integers must hash the same as the ints
734 # Non-integer decimals are normalized and hashed as strings
735 # Normalization assures that hast(100E-1) == hash(10)
738 raise TypeError('Cannot hash a NaN value.')
739 return hash(str(self))
741 if self == Decimal(i):
743 assert self.__nonzero__() # '-0' handled by integer case
744 return hash(str(self.normalize()))
747 """Represents the number as a triple tuple.
749 To show the internals exactly as they are.
751 return (self._sign, self._int, self._exp)
754 """Represents the number as an instance of Decimal."""
755 # Invariant: eval(repr(d)) == d
756 return 'Decimal("%s")' % str(self)
758 def __str__(self, eng = 0, context=None):
759 """Return string representation of the number in scientific notation.
761 Captures all of the information in the underlying representation.
766 minus = '-'*self._sign
767 if self._int == (0,):
770 info = ''.join(map(str, self._int))
771 if self._isnan() == 2:
772 return minus + 'sNaN' + info
773 return minus + 'NaN' + info
774 if self._isinfinity():
775 minus = '-'*self._sign
776 return minus + 'Infinity'
779 context = getcontext()
781 tmp = map(str, self._int)
782 numdigits = len(self._int)
783 leftdigits = self._exp + numdigits
784 if eng and not self: #self = 0eX wants 0[.0[0]]eY, not [[0]0]0eY
785 if self._exp < 0 and self._exp >= -6: #short, no need for e/E
786 s = '-'*self._sign + '0.' + '0'*(abs(self._exp))
788 #exp is closest mult. of 3 >= self._exp
789 exp = ((self._exp - 1)// 3 + 1) * 3
791 s = '0.'+'0'*(exp - self._exp)
800 s += '+' #0.0e+3, not 0.0e3
802 s = '-'*self._sign + s
805 dotplace = (leftdigits-1)%3+1
806 adjexp = leftdigits -1 - (leftdigits-1)%3
808 adjexp = leftdigits-1
812 elif self._exp < 0 and adjexp >= 0:
813 tmp.insert(leftdigits, '.')
814 elif self._exp < 0 and adjexp >= -6:
815 tmp[0:0] = ['0'] * int(-leftdigits)
818 if numdigits > dotplace:
819 tmp.insert(dotplace, '.')
820 elif numdigits < dotplace:
821 tmp.extend(['0']*(dotplace-numdigits))
823 if not context.capitals:
829 tmp.append(str(adjexp))
831 while tmp[0:1] == ['0']:
833 if len(tmp) == 0 or tmp[0] == '.' or tmp[0].lower() == 'e':
840 def to_eng_string(self, context=None):
841 """Convert to engineering-type string.
843 Engineering notation has an exponent which is a multiple of 3, so there
844 are up to 3 digits left of the decimal place.
846 Same rules for when in exponential and when as a value as in __str__.
848 return self.__str__(eng=1, context=context)
850 def __neg__(self, context=None):
851 """Returns a copy with the sign switched.
853 Rounds, if it has reason.
856 ans = self._check_nans(context=context)
861 # -Decimal('0') is Decimal('0'), not Decimal('-0')
869 context = getcontext()
870 if context._rounding_decision == ALWAYS_ROUND:
871 return Decimal((sign, self._int, self._exp))._fix(context)
872 return Decimal( (sign, self._int, self._exp))
874 def __pos__(self, context=None):
875 """Returns a copy, unless it is a sNaN.
877 Rounds the number (if more then precision digits)
880 ans = self._check_nans(context=context)
890 context = getcontext()
892 if context._rounding_decision == ALWAYS_ROUND:
893 ans = self._fix(context)
899 def __abs__(self, round=1, context=None):
900 """Returns the absolute value of self.
902 If the second argument is 0, do not round.
905 ans = self._check_nans(context=context)
911 context = getcontext()
912 context = context._shallow_copy()
913 context._set_rounding_decision(NEVER_ROUND)
916 ans = self.__neg__(context=context)
918 ans = self.__pos__(context=context)
922 def __add__(self, other, context=None):
923 """Returns self + other.
925 -INF + INF (or the reverse) cause InvalidOperation errors.
927 other = _convert_other(other)
928 if other is NotImplemented:
932 context = getcontext()
934 if self._is_special or other._is_special:
935 ans = self._check_nans(other, context)
939 if self._isinfinity():
940 #If both INF, same sign => same as both, opposite => error.
941 if self._sign != other._sign and other._isinfinity():
942 return context._raise_error(InvalidOperation, '-INF + INF')
944 if other._isinfinity():
945 return Decimal(other) #Can't both be infinity here
947 shouldround = context._rounding_decision == ALWAYS_ROUND
949 exp = min(self._exp, other._exp)
951 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
952 #If the answer is 0, the sign should be negative, in this case.
955 if not self and not other:
956 sign = min(self._sign, other._sign)
959 return Decimal( (sign, (0,), exp))
961 exp = max(exp, other._exp - context.prec-1)
962 ans = other._rescale(exp, watchexp=0, context=context)
964 ans = ans._fix(context)
967 exp = max(exp, self._exp - context.prec-1)
968 ans = self._rescale(exp, watchexp=0, context=context)
970 ans = ans._fix(context)
974 op2 = _WorkRep(other)
975 op1, op2 = _normalize(op1, op2, shouldround, context.prec)
978 if op1.sign != op2.sign:
980 if op1.int == op2.int:
981 if exp < context.Etiny():
982 exp = context.Etiny()
983 context._raise_error(Clamped)
984 return Decimal((negativezero, (0,), exp))
985 if op1.int < op2.int:
987 #OK, now abs(op1) > abs(op2)
990 op1.sign, op2.sign = op2.sign, op1.sign
993 #So we know the sign, and op1 > 0.
996 op1.sign, op2.sign = (0, 0)
999 #Now, op1 > abs(op2) > 0
1002 result.int = op1.int + op2.int
1004 result.int = op1.int - op2.int
1006 result.exp = op1.exp
1007 ans = Decimal(result)
1009 ans = ans._fix(context)
1014 def __sub__(self, other, context=None):
1015 """Return self + (-other)"""
1016 other = _convert_other(other)
1017 if other is NotImplemented:
1020 if self._is_special or other._is_special:
1021 ans = self._check_nans(other, context=context)
1025 # -Decimal(0) = Decimal(0), which we don't want since
1026 # (-0 - 0 = -0 + (-0) = -0, but -0 + 0 = 0.)
1027 # so we change the sign directly to a copy
1028 tmp = Decimal(other)
1029 tmp._sign = 1-tmp._sign
1031 return self.__add__(tmp, context=context)
1033 def __rsub__(self, other, context=None):
1034 """Return other + (-self)"""
1035 other = _convert_other(other)
1036 if other is NotImplemented:
1040 tmp._sign = 1 - tmp._sign
1041 return other.__add__(tmp, context=context)
1043 def _increment(self, round=1, context=None):
1044 """Special case of add, adding 1eExponent
1046 Since it is common, (rounding, for example) this adds
1047 (sign)*one E self._exp to the number more efficiently than add.
1050 Decimal('5.624e10')._increment() == Decimal('5.625e10')
1052 if self._is_special:
1053 ans = self._check_nans(context=context)
1057 return Decimal(self) # Must be infinite, and incrementing makes no difference
1062 while L[spot] == 10:
1069 ans = Decimal((self._sign, L, self._exp))
1072 context = getcontext()
1073 if round and context._rounding_decision == ALWAYS_ROUND:
1074 ans = ans._fix(context)
1077 def __mul__(self, other, context=None):
1078 """Return self * other.
1080 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1082 other = _convert_other(other)
1083 if other is NotImplemented:
1087 context = getcontext()
1089 resultsign = self._sign ^ other._sign
1091 if self._is_special or other._is_special:
1092 ans = self._check_nans(other, context)
1096 if self._isinfinity():
1098 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1099 return Infsign[resultsign]
1101 if other._isinfinity():
1103 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1104 return Infsign[resultsign]
1106 resultexp = self._exp + other._exp
1107 shouldround = context._rounding_decision == ALWAYS_ROUND
1109 # Special case for multiplying by zero
1110 if not self or not other:
1111 ans = Decimal((resultsign, (0,), resultexp))
1113 #Fixing in case the exponent is out of bounds
1114 ans = ans._fix(context)
1117 # Special case for multiplying by power of 10
1118 if self._int == (1,):
1119 ans = Decimal((resultsign, other._int, resultexp))
1121 ans = ans._fix(context)
1123 if other._int == (1,):
1124 ans = Decimal((resultsign, self._int, resultexp))
1126 ans = ans._fix(context)
1129 op1 = _WorkRep(self)
1130 op2 = _WorkRep(other)
1132 ans = Decimal( (resultsign, map(int, str(op1.int * op2.int)), resultexp))
1134 ans = ans._fix(context)
1139 def __div__(self, other, context=None):
1140 """Return self / other."""
1141 return self._divide(other, context=context)
1142 __truediv__ = __div__
1144 def _divide(self, other, divmod = 0, context=None):
1145 """Return a / b, to context.prec precision.
1153 Actually, if divmod is 2 or 3 a tuple is returned, but errors for
1154 computing the other value are not raised.
1156 other = _convert_other(other)
1157 if other is NotImplemented:
1158 if divmod in (0, 1):
1159 return NotImplemented
1160 return (NotImplemented, NotImplemented)
1163 context = getcontext()
1165 sign = self._sign ^ other._sign
1167 if self._is_special or other._is_special:
1168 ans = self._check_nans(other, context)
1174 if self._isinfinity() and other._isinfinity():
1176 return (context._raise_error(InvalidOperation,
1177 '(+-)INF // (+-)INF'),
1178 context._raise_error(InvalidOperation,
1179 '(+-)INF % (+-)INF'))
1180 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1182 if self._isinfinity():
1184 return (Infsign[sign],
1185 context._raise_error(InvalidOperation, 'INF % x'))
1187 return (Infsign[sign], NaN)
1189 return (Infsign[sign],
1190 context._raise_error(InvalidOperation, 'INF % x'))
1191 return Infsign[sign]
1193 if other._isinfinity():
1195 return (Decimal((sign, (0,), 0)), Decimal(self))
1196 context._raise_error(Clamped, 'Division by infinity')
1197 return Decimal((sign, (0,), context.Etiny()))
1199 # Special cases for zeroes
1200 if not self and not other:
1202 return context._raise_error(DivisionUndefined, '0 / 0', 1)
1203 return context._raise_error(DivisionUndefined, '0 / 0')
1207 otherside = Decimal(self)
1208 otherside._exp = min(self._exp, other._exp)
1209 return (Decimal((sign, (0,), 0)), otherside)
1210 exp = self._exp - other._exp
1211 if exp < context.Etiny():
1212 exp = context.Etiny()
1213 context._raise_error(Clamped, '0e-x / y')
1214 if exp > context.Emax:
1216 context._raise_error(Clamped, '0e+x / y')
1217 return Decimal( (sign, (0,), exp) )
1221 return context._raise_error(DivisionByZero, 'divmod(x,0)',
1223 return context._raise_error(DivisionByZero, 'x / 0', sign)
1225 #OK, so neither = 0, INF or NaN
1227 shouldround = context._rounding_decision == ALWAYS_ROUND
1229 #If we're dividing into ints, and self < other, stop.
1230 #self.__abs__(0) does not round.
1231 if divmod and (self.__abs__(0, context) < other.__abs__(0, context)):
1233 if divmod == 1 or divmod == 3:
1234 exp = min(self._exp, other._exp)
1235 ans2 = self._rescale(exp, context=context, watchexp=0)
1237 ans2 = ans2._fix(context)
1238 return (Decimal( (sign, (0,), 0) ),
1242 #Don't round the mod part, if we don't need it.
1243 return (Decimal( (sign, (0,), 0) ), Decimal(self))
1245 op1 = _WorkRep(self)
1246 op2 = _WorkRep(other)
1247 op1, op2, adjust = _adjust_coefficients(op1, op2)
1248 res = _WorkRep( (sign, 0, (op1.exp - op2.exp)) )
1249 if divmod and res.exp > context.prec + 1:
1250 return context._raise_error(DivisionImpossible)
1252 prec_limit = 10 ** context.prec
1254 while op2.int <= op1.int:
1257 if res.exp == 0 and divmod:
1258 if res.int >= prec_limit and shouldround:
1259 return context._raise_error(DivisionImpossible)
1260 otherside = Decimal(op1)
1261 frozen = context._ignore_all_flags()
1263 exp = min(self._exp, other._exp)
1264 otherside = otherside._rescale(exp, context=context, watchexp=0)
1265 context._regard_flags(*frozen)
1267 otherside = otherside._fix(context)
1268 return (Decimal(res), otherside)
1270 if op1.int == 0 and adjust >= 0 and not divmod:
1272 if res.int >= prec_limit and shouldround:
1274 return context._raise_error(DivisionImpossible)
1276 # Really, the answer is a bit higher, so adding a one to
1277 # the end will make sure the rounding is right.
1290 if res.exp == 0 and divmod and op2.int > op1.int:
1291 #Solves an error in precision. Same as a previous block.
1293 if res.int >= prec_limit and shouldround:
1294 return context._raise_error(DivisionImpossible)
1295 otherside = Decimal(op1)
1296 frozen = context._ignore_all_flags()
1298 exp = min(self._exp, other._exp)
1299 otherside = otherside._rescale(exp, context=context)
1301 context._regard_flags(*frozen)
1303 return (Decimal(res), otherside)
1307 ans = ans._fix(context)
1310 def __rdiv__(self, other, context=None):
1311 """Swaps self/other and returns __div__."""
1312 other = _convert_other(other)
1313 if other is NotImplemented:
1315 return other.__div__(self, context=context)
1316 __rtruediv__ = __rdiv__
1318 def __divmod__(self, other, context=None):
1320 (self // other, self % other)
1322 return self._divide(other, 1, context)
1324 def __rdivmod__(self, other, context=None):
1325 """Swaps self/other and returns __divmod__."""
1326 other = _convert_other(other)
1327 if other is NotImplemented:
1329 return other.__divmod__(self, context=context)
1331 def __mod__(self, other, context=None):
1335 other = _convert_other(other)
1336 if other is NotImplemented:
1339 if self._is_special or other._is_special:
1340 ans = self._check_nans(other, context)
1344 if self and not other:
1345 return context._raise_error(InvalidOperation, 'x % 0')
1347 return self._divide(other, 3, context)[1]
1349 def __rmod__(self, other, context=None):
1350 """Swaps self/other and returns __mod__."""
1351 other = _convert_other(other)
1352 if other is NotImplemented:
1354 return other.__mod__(self, context=context)
1356 def remainder_near(self, other, context=None):
1358 Remainder nearest to 0- abs(remainder-near) <= other/2
1360 other = _convert_other(other)
1361 if other is NotImplemented:
1364 if self._is_special or other._is_special:
1365 ans = self._check_nans(other, context)
1368 if self and not other:
1369 return context._raise_error(InvalidOperation, 'x % 0')
1372 context = getcontext()
1373 # If DivisionImpossible causes an error, do not leave Rounded/Inexact
1374 # ignored in the calling function.
1375 context = context._shallow_copy()
1376 flags = context._ignore_flags(Rounded, Inexact)
1377 #keep DivisionImpossible flags
1378 (side, r) = self.__divmod__(other, context=context)
1381 context._regard_flags(*flags)
1384 context = context._shallow_copy()
1385 rounding = context._set_rounding_decision(NEVER_ROUND)
1388 comparison = other.__div__(Decimal(-2), context=context)
1390 comparison = other.__div__(Decimal(2), context=context)
1392 context._set_rounding_decision(rounding)
1393 context._regard_flags(*flags)
1395 s1, s2 = r._sign, comparison._sign
1396 r._sign, comparison._sign = 0, 0
1399 r._sign, comparison._sign = s1, s2
1401 self.__divmod__(other, context=context)
1402 return r._fix(context)
1403 r._sign, comparison._sign = s1, s2
1405 rounding = context._set_rounding_decision(NEVER_ROUND)
1407 (side, r) = self.__divmod__(other, context=context)
1408 context._set_rounding_decision(rounding)
1412 decrease = not side._iseven()
1413 rounding = context._set_rounding_decision(NEVER_ROUND)
1414 side = side.__abs__(context=context)
1415 context._set_rounding_decision(rounding)
1417 s1, s2 = r._sign, comparison._sign
1418 r._sign, comparison._sign = 0, 0
1419 if r > comparison or decrease and r == comparison:
1420 r._sign, comparison._sign = s1, s2
1422 if len(side.__add__(Decimal(1), context=context)._int) >= context.prec:
1424 return context._raise_error(DivisionImpossible)[1]
1426 if self._sign == other._sign:
1427 r = r.__sub__(other, context=context)
1429 r = r.__add__(other, context=context)
1431 r._sign, comparison._sign = s1, s2
1433 return r._fix(context)
1435 def __floordiv__(self, other, context=None):
1437 return self._divide(other, 2, context)[0]
1439 def __rfloordiv__(self, other, context=None):
1440 """Swaps self/other and returns __floordiv__."""
1441 other = _convert_other(other)
1442 if other is NotImplemented:
1444 return other.__floordiv__(self, context=context)
1446 def __float__(self):
1447 """Float representation."""
1448 return float(str(self))
1451 """Converts self to an int, truncating if necessary."""
1452 if self._is_special:
1454 context = getcontext()
1455 return context._raise_error(InvalidContext)
1456 elif self._isinfinity():
1457 raise OverflowError, "Cannot convert infinity to long"
1459 s = ''.join(map(str, self._int)) + '0'*self._exp
1461 s = ''.join(map(str, self._int))[:self._exp]
1464 sign = '-'*self._sign
1465 return int(sign + s)
1468 """Converts to a long.
1470 Equivalent to long(int(self))
1472 return long(self.__int__())
1474 def _fix(self, context):
1475 """Round if it is necessary to keep self within prec precision.
1477 Rounds and fixes the exponent. Does not raise on a sNaN.
1480 self - Decimal instance
1481 context - context used.
1483 if self._is_special:
1486 context = getcontext()
1488 ans = self._fixexponents(context)
1489 if len(ans._int) > prec:
1490 ans = ans._round(prec, context=context)
1491 ans = ans._fixexponents(context)
1494 def _fixexponents(self, context):
1495 """Fix the exponents and return a copy with the exponent in bounds.
1496 Only call if known to not be a special value.
1498 folddown = context._clamp
1501 ans_adjusted = ans.adjusted()
1502 if ans_adjusted < Emin:
1503 Etiny = context.Etiny()
1504 if ans._exp < Etiny:
1508 context._raise_error(Clamped)
1510 ans = ans._rescale(Etiny, context=context)
1511 #It isn't zero, and exp < Emin => subnormal
1512 context._raise_error(Subnormal)
1513 if context.flags[Inexact]:
1514 context._raise_error(Underflow)
1517 #Only raise subnormal if non-zero.
1518 context._raise_error(Subnormal)
1520 Etop = context.Etop()
1521 if folddown and ans._exp > Etop:
1522 context._raise_error(Clamped)
1523 ans = ans._rescale(Etop, context=context)
1526 if ans_adjusted > Emax:
1530 context._raise_error(Clamped)
1532 context._raise_error(Inexact)
1533 context._raise_error(Rounded)
1534 return context._raise_error(Overflow, 'above Emax', ans._sign)
1537 def _round(self, prec=None, rounding=None, context=None):
1538 """Returns a rounded version of self.
1540 You can specify the precision or rounding method. Otherwise, the
1541 context determines it.
1544 if self._is_special:
1545 ans = self._check_nans(context=context)
1549 if self._isinfinity():
1550 return Decimal(self)
1553 context = getcontext()
1555 if rounding is None:
1556 rounding = context.rounding
1563 exp = len(self._int) - prec + self._exp
1566 exp = len(self._int) + self._exp - prec
1567 ans = Decimal((self._sign, dig, exp))
1568 context._raise_error(Rounded)
1572 temp = Decimal(self)
1573 temp._int = (0,)+temp._int
1576 exp = self._exp + len(self._int) - prec - 1
1577 temp = Decimal( (self._sign, (0, 1), exp))
1580 temp = Decimal(self)
1582 numdigits = len(temp._int)
1583 if prec == numdigits:
1586 # See if we need to extend precision
1587 expdiff = prec - numdigits
1589 tmp = list(temp._int)
1590 tmp.extend([0] * expdiff)
1591 ans = Decimal( (temp._sign, tmp, temp._exp - expdiff))
1594 #OK, but maybe all the lost digits are 0.
1595 lostdigits = self._int[expdiff:]
1596 if lostdigits == (0,) * len(lostdigits):
1597 ans = Decimal( (temp._sign, temp._int[:prec], temp._exp - expdiff))
1598 #Rounded, but not Inexact
1599 context._raise_error(Rounded)
1602 # Okay, let's round and lose data
1604 this_function = getattr(temp, self._pick_rounding_function[rounding])
1605 #Now we've got the rounding function
1607 if prec != context.prec:
1608 context = context._shallow_copy()
1610 ans = this_function(prec, expdiff, context)
1611 context._raise_error(Rounded)
1612 context._raise_error(Inexact, 'Changed in rounding')
1616 _pick_rounding_function = {}
1618 def _round_down(self, prec, expdiff, context):
1619 """Also known as round-towards-0, truncate."""
1620 return Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1622 def _round_half_up(self, prec, expdiff, context, tmp = None):
1623 """Rounds 5 up (away from 0)"""
1626 tmp = Decimal( (self._sign,self._int[:prec], self._exp - expdiff))
1627 if self._int[prec] >= 5:
1628 tmp = tmp._increment(round=0, context=context)
1629 if len(tmp._int) > prec:
1630 return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1633 def _round_half_even(self, prec, expdiff, context):
1634 """Round 5 to even, rest to nearest."""
1636 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1637 half = (self._int[prec] == 5)
1639 for digit in self._int[prec+1:]:
1644 if self._int[prec-1] & 1 == 0:
1646 return self._round_half_up(prec, expdiff, context, tmp)
1648 def _round_half_down(self, prec, expdiff, context):
1651 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff))
1652 half = (self._int[prec] == 5)
1654 for digit in self._int[prec+1:]:
1660 return self._round_half_up(prec, expdiff, context, tmp)
1662 def _round_up(self, prec, expdiff, context):
1663 """Rounds away from 0."""
1664 tmp = Decimal( (self._sign, self._int[:prec], self._exp - expdiff) )
1665 for digit in self._int[prec:]:
1667 tmp = tmp._increment(round=1, context=context)
1668 if len(tmp._int) > prec:
1669 return Decimal( (tmp._sign, tmp._int[:-1], tmp._exp + 1))
1674 def _round_ceiling(self, prec, expdiff, context):
1675 """Rounds up (not away from 0 if negative.)"""
1677 return self._round_down(prec, expdiff, context)
1679 return self._round_up(prec, expdiff, context)
1681 def _round_floor(self, prec, expdiff, context):
1682 """Rounds down (not towards 0 if negative)"""
1684 return self._round_down(prec, expdiff, context)
1686 return self._round_up(prec, expdiff, context)
1688 def __pow__(self, n, modulo = None, context=None):
1689 """Return self ** n (mod modulo)
1691 If modulo is None (default), don't take it mod modulo.
1693 n = _convert_other(n)
1694 if n is NotImplemented:
1698 context = getcontext()
1700 if self._is_special or n._is_special or n.adjusted() > 8:
1701 #Because the spot << doesn't work with really big exponents
1702 if n._isinfinity() or n.adjusted() > 8:
1703 return context._raise_error(InvalidOperation, 'x ** INF')
1705 ans = self._check_nans(n, context)
1709 if not n._isinteger():
1710 return context._raise_error(InvalidOperation, 'x ** (non-integer)')
1712 if not self and not n:
1713 return context._raise_error(InvalidOperation, '0 ** 0')
1718 if self == Decimal(1):
1721 sign = self._sign and not n._iseven()
1724 if self._isinfinity():
1726 return context._raise_error(InvalidOperation, 'INF % x')
1728 return Infsign[sign]
1729 return Decimal( (sign, (0,), 0) )
1731 #with ludicrously large exponent, just raise an overflow and return inf.
1732 if not modulo and n > 0 and (self._exp + len(self._int) - 1) * n > context.Emax \
1735 tmp = Decimal('inf')
1737 context._raise_error(Rounded)
1738 context._raise_error(Inexact)
1739 context._raise_error(Overflow, 'Big power', sign)
1742 elength = len(str(abs(n)))
1743 firstprec = context.prec
1745 if not modulo and firstprec + elength + 1 > DefaultContext.Emax:
1746 return context._raise_error(Overflow, 'Too much precision.', sign)
1750 context = context._shallow_copy()
1751 context.prec = firstprec + elength + 1
1753 #n is a long now, not Decimal instance
1755 mul = Decimal(1).__div__(mul, context=context)
1762 #Spot is the highest power of 2 less than n
1764 val = val.__mul__(val, context=context)
1765 if val._isinfinity():
1769 val = val.__mul__(mul, context=context)
1770 if modulo is not None:
1771 val = val.__mod__(modulo, context=context)
1773 context.prec = firstprec
1775 if context._rounding_decision == ALWAYS_ROUND:
1776 return val._fix(context)
1779 def __rpow__(self, other, context=None):
1780 """Swaps self/other and returns __pow__."""
1781 other = _convert_other(other)
1782 if other is NotImplemented:
1784 return other.__pow__(self, context=context)
1786 def normalize(self, context=None):
1787 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
1789 if self._is_special:
1790 ans = self._check_nans(context=context)
1794 dup = self._fix(context)
1795 if dup._isinfinity():
1799 return Decimal( (dup._sign, (0,), 0) )
1802 while dup._int[end-1] == 0:
1805 return Decimal( (dup._sign, dup._int[:end], exp) )
1808 def quantize(self, exp, rounding=None, context=None, watchexp=1):
1809 """Quantize self so its exponent is the same as that of exp.
1811 Similar to self._rescale(exp._exp) but with error checking.
1813 if self._is_special or exp._is_special:
1814 ans = self._check_nans(exp, context)
1818 if exp._isinfinity() or self._isinfinity():
1819 if exp._isinfinity() and self._isinfinity():
1820 return self #if both are inf, it is OK
1822 context = getcontext()
1823 return context._raise_error(InvalidOperation,
1824 'quantize with one INF')
1825 return self._rescale(exp._exp, rounding, context, watchexp)
1827 def same_quantum(self, other):
1828 """Test whether self and other have the same exponent.
1830 same as self._exp == other._exp, except NaN == sNaN
1832 if self._is_special or other._is_special:
1833 if self._isnan() or other._isnan():
1834 return self._isnan() and other._isnan() and True
1835 if self._isinfinity() or other._isinfinity():
1836 return self._isinfinity() and other._isinfinity() and True
1837 return self._exp == other._exp
1839 def _rescale(self, exp, rounding=None, context=None, watchexp=1):
1840 """Rescales so that the exponent is exp.
1842 exp = exp to scale to (an integer)
1843 rounding = rounding version
1844 watchexp: if set (default) an error is returned if exp is greater
1845 than Emax or less than Etiny.
1848 context = getcontext()
1850 if self._is_special:
1851 if self._isinfinity():
1852 return context._raise_error(InvalidOperation, 'rescale with an INF')
1854 ans = self._check_nans(context=context)
1858 if watchexp and (context.Emax < exp or context.Etiny() > exp):
1859 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1867 diff = self._exp - exp
1868 digits = len(self._int) + diff
1870 if watchexp and digits > context.prec:
1871 return context._raise_error(InvalidOperation, 'Rescale > prec')
1874 tmp._int = (0,) + tmp._int
1878 tmp._exp = -digits + tmp._exp
1881 tmp = tmp._round(digits, rounding, context=context)
1883 if tmp._int[0] == 0 and len(tmp._int) > 1:
1884 tmp._int = tmp._int[1:]
1887 tmp_adjusted = tmp.adjusted()
1888 if tmp and tmp_adjusted < context.Emin:
1889 context._raise_error(Subnormal)
1890 elif tmp and tmp_adjusted > context.Emax:
1891 return context._raise_error(InvalidOperation, 'rescale(a, INF)')
1894 def to_integral(self, rounding=None, context=None):
1895 """Rounds to the nearest integer, without raising inexact, rounded."""
1896 if self._is_special:
1897 ans = self._check_nans(context=context)
1903 context = getcontext()
1904 flags = context._ignore_flags(Rounded, Inexact)
1905 ans = self._rescale(0, rounding, context=context)
1906 context._regard_flags(flags)
1909 def sqrt(self, context=None):
1910 """Return the square root of self.
1912 Uses a converging algorithm (Xn+1 = 0.5*(Xn + self / Xn))
1913 Should quadratically approach the right answer.
1915 if self._is_special:
1916 ans = self._check_nans(context=context)
1920 if self._isinfinity() and self._sign == 0:
1921 return Decimal(self)
1924 #exponent = self._exp / 2, using round_down.
1926 # exp = (self._exp+1) // 2
1928 exp = (self._exp) // 2
1931 return Decimal( (1, (0,), exp))
1933 return Decimal( (0, (0,), exp))
1936 context = getcontext()
1939 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
1943 expadd = tmp._exp // 2
1950 context = context._shallow_copy()
1951 flags = context._ignore_all_flags()
1952 firstprec = context.prec
1954 if tmp.adjusted() & 1 == 0:
1955 ans = Decimal( (0, (8,1,9), tmp.adjusted() - 2) )
1956 ans = ans.__add__(tmp.__mul__(Decimal((0, (2,5,9), -2)),
1957 context=context), context=context)
1958 ans._exp -= 1 + tmp.adjusted() // 2
1960 ans = Decimal( (0, (2,5,9), tmp._exp + len(tmp._int)- 3) )
1961 ans = ans.__add__(tmp.__mul__(Decimal((0, (8,1,9), -3)),
1962 context=context), context=context)
1963 ans._exp -= 1 + tmp.adjusted() // 2
1965 #ans is now a linear approximation.
1967 Emax, Emin = context.Emax, context.Emin
1968 context.Emax, context.Emin = DefaultContext.Emax, DefaultContext.Emin
1970 half = Decimal('0.5')
1972 maxp = firstprec + 2
1973 rounding = context._set_rounding(ROUND_HALF_EVEN)
1975 context.prec = min(2*context.prec - 2, maxp)
1976 ans = half.__mul__(ans.__add__(tmp.__div__(ans, context=context),
1977 context=context), context=context)
1978 if context.prec == maxp:
1981 #round to the answer's precision-- the only error can be 1 ulp.
1982 context.prec = firstprec
1983 prevexp = ans.adjusted()
1984 ans = ans._round(context=context)
1986 #Now, check if the other last digits are better.
1987 context.prec = firstprec + 1
1988 # In case we rounded up another digit and we should actually go lower.
1989 if prevexp != ans.adjusted():
1994 lower = ans.__sub__(Decimal((0, (5,), ans._exp-1)), context=context)
1995 context._set_rounding(ROUND_UP)
1996 if lower.__mul__(lower, context=context) > (tmp):
1997 ans = ans.__sub__(Decimal((0, (1,), ans._exp)), context=context)
2000 upper = ans.__add__(Decimal((0, (5,), ans._exp-1)),context=context)
2001 context._set_rounding(ROUND_DOWN)
2002 if upper.__mul__(upper, context=context) < tmp:
2003 ans = ans.__add__(Decimal((0, (1,), ans._exp)),context=context)
2007 context.prec = firstprec
2008 context.rounding = rounding
2009 ans = ans._fix(context)
2011 rounding = context._set_rounding_decision(NEVER_ROUND)
2012 if not ans.__mul__(ans, context=context) == self:
2013 # Only rounded/inexact if here.
2014 context._regard_flags(flags)
2015 context._raise_error(Rounded)
2016 context._raise_error(Inexact)
2018 #Exact answer, so let's set the exponent right.
2020 # exp = (self._exp +1)// 2
2022 exp = self._exp // 2
2023 context.prec += ans._exp - exp
2024 ans = ans._rescale(exp, context=context)
2025 context.prec = firstprec
2026 context._regard_flags(flags)
2027 context.Emax, context.Emin = Emax, Emin
2029 return ans._fix(context)
2031 def max(self, other, context=None):
2032 """Returns the larger value.
2034 like max(self, other) except if one is not a number, returns
2035 NaN (and signals if one is sNaN). Also rounds.
2037 other = _convert_other(other)
2038 if other is NotImplemented:
2041 if self._is_special or other._is_special:
2042 # if one operand is a quiet NaN and the other is number, then the
2043 # number is always returned
2047 if on == 1 and sn != 2:
2049 if sn == 1 and on != 2:
2051 return self._check_nans(other, context)
2054 c = self.__cmp__(other)
2056 # if both operands are finite and equal in numerical value
2057 # then an ordering is applied:
2059 # if the signs differ then max returns the operand with the
2060 # positive sign and min returns the operand with the negative sign
2062 # if the signs are the same then the exponent is used to select
2064 if self._sign != other._sign:
2067 elif self._exp < other._exp and not self._sign:
2069 elif self._exp > other._exp and self._sign:
2075 context = getcontext()
2076 if context._rounding_decision == ALWAYS_ROUND:
2077 return ans._fix(context)
2080 def min(self, other, context=None):
2081 """Returns the smaller value.
2083 like min(self, other) except if one is not a number, returns
2084 NaN (and signals if one is sNaN). Also rounds.
2086 other = _convert_other(other)
2087 if other is NotImplemented:
2090 if self._is_special or other._is_special:
2091 # if one operand is a quiet NaN and the other is number, then the
2092 # number is always returned
2096 if on == 1 and sn != 2:
2098 if sn == 1 and on != 2:
2100 return self._check_nans(other, context)
2103 c = self.__cmp__(other)
2105 # if both operands are finite and equal in numerical value
2106 # then an ordering is applied:
2108 # if the signs differ then max returns the operand with the
2109 # positive sign and min returns the operand with the negative sign
2111 # if the signs are the same then the exponent is used to select
2113 if self._sign != other._sign:
2116 elif self._exp > other._exp and not self._sign:
2118 elif self._exp < other._exp and self._sign:
2124 context = getcontext()
2125 if context._rounding_decision == ALWAYS_ROUND:
2126 return ans._fix(context)
2129 def _isinteger(self):
2130 """Returns whether self is an integer"""
2133 rest = self._int[self._exp:]
2134 return rest == (0,)*len(rest)
2137 """Returns 1 if self is even. Assumes self is an integer."""
2140 return self._int[-1+self._exp] & 1 == 0
2143 """Return the adjusted exponent of self"""
2145 return self._exp + len(self._int) - 1
2146 #If NaN or Infinity, self._exp is string
2150 # support for pickling, copy, and deepcopy
2151 def __reduce__(self):
2152 return (self.__class__, (str(self),))
2155 if type(self) == Decimal:
2156 return self # I'm immutable; therefore I am my own clone
2157 return self.__class__(str(self))
2159 def __deepcopy__(self, memo):
2160 if type(self) == Decimal:
2161 return self # My components are also immutable
2162 return self.__class__(str(self))
2164 ##### Context class ###########################################
2167 # get rounding method function:
2168 rounding_functions = [name for name in Decimal.__dict__.keys() if name.startswith('_round_')]
2169 for name in rounding_functions:
2170 #name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
2171 globalname = name[1:].upper()
2172 val = globals()[globalname]
2173 Decimal._pick_rounding_function[val] = name
2175 del name, val, globalname, rounding_functions
2177 class Context(object):
2178 """Contains the context for a Decimal instance.
2181 prec - precision (for use in rounding, division, square roots..)
2182 rounding - rounding type. (how you round)
2183 _rounding_decision - ALWAYS_ROUND, NEVER_ROUND -- do you round?
2184 traps - If traps[exception] = 1, then the exception is
2185 raised when it is caused. Otherwise, a value is
2187 flags - When an exception is caused, flags[exception] is incremented.
2188 (Whether or not the trap_enabler is set)
2189 Should be reset by user of Decimal instance.
2190 Emin - Minimum exponent
2191 Emax - Maximum exponent
2192 capitals - If 1, 1*10^1 is printed as 1E+1.
2193 If 0, printed as 1e1
2194 _clamp - If 1, change exponents if too high (Default 0)
2197 def __init__(self, prec=None, rounding=None,
2198 traps=None, flags=None,
2199 _rounding_decision=None,
2200 Emin=None, Emax=None,
2201 capitals=None, _clamp=0,
2202 _ignored_flags=None):
2205 if _ignored_flags is None:
2207 if not isinstance(flags, dict):
2208 flags = dict([(s,s in flags) for s in _signals])
2210 if traps is not None and not isinstance(traps, dict):
2211 traps = dict([(s,s in traps) for s in _signals])
2213 for name, val in locals().items():
2215 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
2217 setattr(self, name, val)
2221 """Show the current context."""
2223 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d' % vars(self))
2224 s.append('flags=[' + ', '.join([f.__name__ for f, v in self.flags.items() if v]) + ']')
2225 s.append('traps=[' + ', '.join([t.__name__ for t, v in self.traps.items() if v]) + ']')
2226 return ', '.join(s) + ')'
2228 def clear_flags(self):
2229 """Reset all flags to zero"""
2230 for flag in self.flags:
2231 self.flags[flag] = 0
2233 def _shallow_copy(self):
2234 """Returns a shallow copy from self."""
2235 nc = Context(self.prec, self.rounding, self.traps, self.flags,
2236 self._rounding_decision, self.Emin, self.Emax,
2237 self.capitals, self._clamp, self._ignored_flags)
2241 """Returns a deep copy from self."""
2242 nc = Context(self.prec, self.rounding, self.traps.copy(), self.flags.copy(),
2243 self._rounding_decision, self.Emin, self.Emax,
2244 self.capitals, self._clamp, self._ignored_flags)
2248 def _raise_error(self, condition, explanation = None, *args):
2251 If the flag is in _ignored_flags, returns the default response.
2252 Otherwise, it increments the flag, then, if the corresponding
2253 trap_enabler is set, it reaises the exception. Otherwise, it returns
2254 the default value after incrementing the flag.
2256 error = _condition_map.get(condition, condition)
2257 if error in self._ignored_flags:
2258 #Don't touch the flag
2259 return error().handle(self, *args)
2261 self.flags[error] += 1
2262 if not self.traps[error]:
2263 #The errors define how to handle themselves.
2264 return condition().handle(self, *args)
2266 # Errors should only be risked on copies of the context
2267 #self._ignored_flags = []
2268 raise error, explanation
2270 def _ignore_all_flags(self):
2271 """Ignore all flags, if they are raised"""
2272 return self._ignore_flags(*_signals)
2274 def _ignore_flags(self, *flags):
2275 """Ignore the flags, if they are raised"""
2276 # Do not mutate-- This way, copies of a context leave the original
2278 self._ignored_flags = (self._ignored_flags + list(flags))
2281 def _regard_flags(self, *flags):
2282 """Stop ignoring the flags, if they are raised"""
2283 if flags and isinstance(flags[0], (tuple,list)):
2286 self._ignored_flags.remove(flag)
2289 """A Context cannot be hashed."""
2290 # We inherit object.__hash__, so we must deny this explicitly
2291 raise TypeError, "Cannot hash a Context."
2294 """Returns Etiny (= Emin - prec + 1)"""
2295 return int(self.Emin - self.prec + 1)
2298 """Returns maximum exponent (= Emax - prec + 1)"""
2299 return int(self.Emax - self.prec + 1)
2301 def _set_rounding_decision(self, type):
2302 """Sets the rounding decision.
2304 Sets the rounding decision, and returns the current (previous)
2305 rounding decision. Often used like:
2307 context = context._shallow_copy()
2308 # That so you don't change the calling context
2309 # if an error occurs in the middle (say DivisionImpossible is raised).
2311 rounding = context._set_rounding_decision(NEVER_ROUND)
2312 instance = instance / Decimal(2)
2313 context._set_rounding_decision(rounding)
2315 This will make it not round for that operation.
2318 rounding = self._rounding_decision
2319 self._rounding_decision = type
2322 def _set_rounding(self, type):
2323 """Sets the rounding type.
2325 Sets the rounding type, and returns the current (previous)
2326 rounding type. Often used like:
2328 context = context.copy()
2329 # so you don't change the calling context
2330 # if an error occurs in the middle.
2331 rounding = context._set_rounding(ROUND_UP)
2332 val = self.__sub__(other, context=context)
2333 context._set_rounding(rounding)
2335 This will make it round up for that operation.
2337 rounding = self.rounding
2341 def create_decimal(self, num='0'):
2342 """Creates a new Decimal instance but using self as context."""
2343 d = Decimal(num, context=self)
2348 """Returns the absolute value of the operand.
2350 If the operand is negative, the result is the same as using the minus
2351 operation on the operand. Otherwise, the result is the same as using
2352 the plus operation on the operand.
2354 >>> ExtendedContext.abs(Decimal('2.1'))
2356 >>> ExtendedContext.abs(Decimal('-100'))
2358 >>> ExtendedContext.abs(Decimal('101.5'))
2360 >>> ExtendedContext.abs(Decimal('-101.5'))
2363 return a.__abs__(context=self)
2365 def add(self, a, b):
2366 """Return the sum of the two operands.
2368 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
2370 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
2373 return a.__add__(b, context=self)
2375 def _apply(self, a):
2376 return str(a._fix(self))
2378 def compare(self, a, b):
2379 """Compares values numerically.
2381 If the signs of the operands differ, a value representing each operand
2382 ('-1' if the operand is less than zero, '0' if the operand is zero or
2383 negative zero, or '1' if the operand is greater than zero) is used in
2384 place of that operand for the comparison instead of the actual
2387 The comparison is then effected by subtracting the second operand from
2388 the first and then returning a value according to the result of the
2389 subtraction: '-1' if the result is less than zero, '0' if the result is
2390 zero or negative zero, or '1' if the result is greater than zero.
2392 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
2394 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
2396 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
2398 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
2400 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
2402 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
2405 return a.compare(b, context=self)
2407 def divide(self, a, b):
2408 """Decimal division in a specified context.
2410 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
2411 Decimal("0.333333333")
2412 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
2413 Decimal("0.666666667")
2414 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
2416 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
2418 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
2420 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
2422 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
2424 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
2426 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
2428 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
2431 return a.__div__(b, context=self)
2433 def divide_int(self, a, b):
2434 """Divides two numbers and returns the integer part of the result.
2436 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
2438 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
2440 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
2443 return a.__floordiv__(b, context=self)
2445 def divmod(self, a, b):
2446 return a.__divmod__(b, context=self)
2449 """max compares two values numerically and returns the maximum.
2451 If either operand is a NaN then the general rules apply.
2452 Otherwise, the operands are compared as as though by the compare
2453 operation. If they are numerically equal then the left-hand operand
2454 is chosen as the result. Otherwise the maximum (closer to positive
2455 infinity) of the two operands is chosen as the result.
2457 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
2459 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
2461 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
2463 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
2466 return a.max(b, context=self)
2469 """min compares two values numerically and returns the minimum.
2471 If either operand is a NaN then the general rules apply.
2472 Otherwise, the operands are compared as as though by the compare
2473 operation. If they are numerically equal then the left-hand operand
2474 is chosen as the result. Otherwise the minimum (closer to negative
2475 infinity) of the two operands is chosen as the result.
2477 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
2479 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
2481 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
2483 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
2486 return a.min(b, context=self)
2489 """Minus corresponds to unary prefix minus in Python.
2491 The operation is evaluated using the same rules as subtract; the
2492 operation minus(a) is calculated as subtract('0', a) where the '0'
2493 has the same exponent as the operand.
2495 >>> ExtendedContext.minus(Decimal('1.3'))
2497 >>> ExtendedContext.minus(Decimal('-1.3'))
2500 return a.__neg__(context=self)
2502 def multiply(self, a, b):
2503 """multiply multiplies two operands.
2505 If either operand is a special value then the general rules apply.
2506 Otherwise, the operands are multiplied together ('long multiplication'),
2507 resulting in a number which may be as long as the sum of the lengths
2508 of the two operands.
2510 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
2512 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
2514 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
2516 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
2518 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
2519 Decimal("4.28135971E+11")
2521 return a.__mul__(b, context=self)
2523 def normalize(self, a):
2524 """normalize reduces an operand to its simplest form.
2526 Essentially a plus operation with all trailing zeros removed from the
2529 >>> ExtendedContext.normalize(Decimal('2.1'))
2531 >>> ExtendedContext.normalize(Decimal('-2.0'))
2533 >>> ExtendedContext.normalize(Decimal('1.200'))
2535 >>> ExtendedContext.normalize(Decimal('-120'))
2537 >>> ExtendedContext.normalize(Decimal('120.00'))
2539 >>> ExtendedContext.normalize(Decimal('0.00'))
2542 return a.normalize(context=self)
2545 """Plus corresponds to unary prefix plus in Python.
2547 The operation is evaluated using the same rules as add; the
2548 operation plus(a) is calculated as add('0', a) where the '0'
2549 has the same exponent as the operand.
2551 >>> ExtendedContext.plus(Decimal('1.3'))
2553 >>> ExtendedContext.plus(Decimal('-1.3'))
2556 return a.__pos__(context=self)
2558 def power(self, a, b, modulo=None):
2559 """Raises a to the power of b, to modulo if given.
2561 The right-hand operand must be a whole number whose integer part (after
2562 any exponent has been applied) has no more than 9 digits and whose
2563 fractional part (if any) is all zeros before any rounding. The operand
2564 may be positive, negative, or zero; if negative, the absolute value of
2565 the power is used, and the left-hand operand is inverted (divided into
2568 If the increased precision needed for the intermediate calculations
2569 exceeds the capabilities of the implementation then an Invalid operation
2570 condition is raised.
2572 If, when raising to a negative power, an underflow occurs during the
2573 division into 1, the operation is not halted at that point but
2576 >>> ExtendedContext.power(Decimal('2'), Decimal('3'))
2578 >>> ExtendedContext.power(Decimal('2'), Decimal('-3'))
2580 >>> ExtendedContext.power(Decimal('1.7'), Decimal('8'))
2581 Decimal("69.7575744")
2582 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-2'))
2584 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('-1'))
2586 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('0'))
2588 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('1'))
2590 >>> ExtendedContext.power(Decimal('Infinity'), Decimal('2'))
2592 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-2'))
2594 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('-1'))
2596 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('0'))
2598 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('1'))
2599 Decimal("-Infinity")
2600 >>> ExtendedContext.power(Decimal('-Infinity'), Decimal('2'))
2602 >>> ExtendedContext.power(Decimal('0'), Decimal('0'))
2605 return a.__pow__(b, modulo, context=self)
2607 def quantize(self, a, b):
2608 """Returns a value equal to 'a' (rounded) and having the exponent of 'b'.
2610 The coefficient of the result is derived from that of the left-hand
2611 operand. It may be rounded using the current rounding setting (if the
2612 exponent is being increased), multiplied by a positive power of ten (if
2613 the exponent is being decreased), or is unchanged (if the exponent is
2614 already equal to that of the right-hand operand).
2616 Unlike other operations, if the length of the coefficient after the
2617 quantize operation would be greater than precision then an Invalid
2618 operation condition is raised. This guarantees that, unless there is an
2619 error condition, the exponent of the result of a quantize is always
2620 equal to that of the right-hand operand.
2622 Also unlike other operations, quantize will never raise Underflow, even
2623 if the result is subnormal and inexact.
2625 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
2627 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
2629 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
2631 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
2633 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
2635 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
2636 Decimal("-Infinity")
2637 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
2639 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
2641 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
2643 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
2645 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
2647 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
2649 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
2651 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
2653 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
2656 return a.quantize(b, context=self)
2658 def remainder(self, a, b):
2659 """Returns the remainder from integer division.
2661 The result is the residue of the dividend after the operation of
2662 calculating integer division as described for divide-integer, rounded to
2663 precision digits if necessary. The sign of the result, if non-zero, is
2664 the same as that of the original dividend.
2666 This operation will fail under the same conditions as integer division
2667 (that is, if integer division on the same two operands would fail, the
2668 remainder cannot be calculated).
2670 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
2672 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
2674 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
2676 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
2678 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
2680 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
2683 return a.__mod__(b, context=self)
2685 def remainder_near(self, a, b):
2686 """Returns to be "a - b * n", where n is the integer nearest the exact
2687 value of "x / b" (if two integers are equally near then the even one
2688 is chosen). If the result is equal to 0 then its sign will be the
2691 This operation will fail under the same conditions as integer division
2692 (that is, if integer division on the same two operands would fail, the
2693 remainder cannot be calculated).
2695 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
2697 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
2699 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
2701 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
2703 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
2705 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
2707 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
2710 return a.remainder_near(b, context=self)
2712 def same_quantum(self, a, b):
2713 """Returns True if the two operands have the same exponent.
2715 The result is never affected by either the sign or the coefficient of
2718 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
2720 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
2722 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
2724 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
2727 return a.same_quantum(b)
2730 """Returns the square root of a non-negative number to context precision.
2732 If the result must be inexact, it is rounded using the round-half-even
2735 >>> ExtendedContext.sqrt(Decimal('0'))
2737 >>> ExtendedContext.sqrt(Decimal('-0'))
2739 >>> ExtendedContext.sqrt(Decimal('0.39'))
2740 Decimal("0.624499800")
2741 >>> ExtendedContext.sqrt(Decimal('100'))
2743 >>> ExtendedContext.sqrt(Decimal('1'))
2745 >>> ExtendedContext.sqrt(Decimal('1.0'))
2747 >>> ExtendedContext.sqrt(Decimal('1.00'))
2749 >>> ExtendedContext.sqrt(Decimal('7'))
2750 Decimal("2.64575131")
2751 >>> ExtendedContext.sqrt(Decimal('10'))
2752 Decimal("3.16227766")
2753 >>> ExtendedContext.prec
2756 return a.sqrt(context=self)
2758 def subtract(self, a, b):
2759 """Return the difference between the two operands.
2761 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
2763 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
2765 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
2768 return a.__sub__(b, context=self)
2770 def to_eng_string(self, a):
2771 """Converts a number to a string, using scientific notation.
2773 The operation is not affected by the context.
2775 return a.to_eng_string(context=self)
2777 def to_sci_string(self, a):
2778 """Converts a number to a string, using scientific notation.
2780 The operation is not affected by the context.
2782 return a.__str__(context=self)
2784 def to_integral(self, a):
2785 """Rounds to an integer.
2787 When the operand has a negative exponent, the result is the same
2788 as using the quantize() operation using the given operand as the
2789 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
2790 of the operand as the precision setting, except that no flags will
2791 be set. The rounding mode is taken from the context.
2793 >>> ExtendedContext.to_integral(Decimal('2.1'))
2795 >>> ExtendedContext.to_integral(Decimal('100'))
2797 >>> ExtendedContext.to_integral(Decimal('100.0'))
2799 >>> ExtendedContext.to_integral(Decimal('101.5'))
2801 >>> ExtendedContext.to_integral(Decimal('-101.5'))
2803 >>> ExtendedContext.to_integral(Decimal('10E+5'))
2805 >>> ExtendedContext.to_integral(Decimal('7.89E+77'))
2807 >>> ExtendedContext.to_integral(Decimal('-Inf'))
2808 Decimal("-Infinity")
2810 return a.to_integral(context=self)
2812 class _WorkRep(object):
2813 __slots__ = ('sign','int','exp')
2816 # exp: None, int, or string
2818 def __init__(self, value=None):
2823 elif isinstance(value, Decimal):
2824 self.sign = value._sign
2826 for digit in value._int:
2827 cum = cum * 10 + digit
2829 self.exp = value._exp
2831 # assert isinstance(value, tuple)
2832 self.sign = value[0]
2837 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
2843 def _normalize(op1, op2, shouldround = 0, prec = 0):
2844 """Normalizes op1, op2 to have the same exp and length of coefficient.
2846 Done during addition.
2848 # Yes, the exponent is a long, but the difference between exponents
2849 # must be an int-- otherwise you'd get a big memory problem.
2850 numdigits = int(op1.exp - op2.exp)
2852 numdigits = -numdigits
2860 if shouldround and numdigits > prec + 1:
2861 # Big difference in exponents - check the adjusted exponents
2862 tmp_len = len(str(tmp.int))
2863 other_len = len(str(other.int))
2864 if numdigits > (other_len + prec + 1 - tmp_len):
2865 # If the difference in adjusted exps is > prec+1, we know
2866 # other is insignificant, so might as well put a 1 after the precision.
2867 # (since this is only for addition.) Also stops use of massive longs.
2869 extend = prec + 2 - tmp_len
2872 tmp.int *= 10 ** extend
2878 tmp.int *= 10 ** numdigits
2879 tmp.exp -= numdigits
2882 def _adjust_coefficients(op1, op2):
2883 """Adjust op1, op2 so that op2.int * 10 > op1.int >= op2.int.
2885 Returns the adjusted op1, op2 as well as the change in op1.exp-op2.exp.
2887 Used on _WorkRep instances during division.
2890 #If op1 is smaller, make it larger
2891 while op2.int > op1.int:
2896 #If op2 is too small, make it larger
2897 while op1.int >= (10 * op2.int):
2902 return op1, op2, adjust
2904 ##### Helper Functions ########################################
2906 def _convert_other(other):
2907 """Convert other to Decimal.
2909 Verifies that it's ok to use in an implicit construction.
2911 if isinstance(other, Decimal):
2913 if isinstance(other, (int, long)):
2914 return Decimal(other)
2915 return NotImplemented
2926 def _isinfinity(num):
2927 """Determines whether a string or float is infinity.
2929 +1 for negative infinity; 0 for finite ; +1 for positive infinity
2931 num = str(num).lower()
2932 return _infinity_map.get(num, 0)
2935 """Determines whether a string or float is NaN
2937 (1, sign, diagnostic info as string) => NaN
2938 (2, sign, diagnostic info as string) => sNaN
2941 num = str(num).lower()
2945 #get the sign, get rid of trailing [+-]
2949 elif num[0] == '-': #elif avoids '+-nan'
2953 if num.startswith('nan'):
2954 if len(num) > 3 and not num[3:].isdigit(): #diagnostic info
2956 return (1, sign, num[3:].lstrip('0'))
2957 if num.startswith('snan'):
2958 if len(num) > 4 and not num[4:].isdigit():
2960 return (2, sign, num[4:].lstrip('0'))
2964 ##### Setup Specific Contexts ################################
2966 # The default context prototype used by Context()
2967 # Is mutable, so that new contexts can have different default values
2969 DefaultContext = Context(
2970 prec=28, rounding=ROUND_HALF_EVEN,
2971 traps=[DivisionByZero, Overflow, InvalidOperation],
2973 _rounding_decision=ALWAYS_ROUND,
2979 # Pre-made alternate contexts offered by the specification
2980 # Don't change these; the user should be able to select these
2981 # contexts and be able to reproduce results from other implementations
2984 BasicContext = Context(
2985 prec=9, rounding=ROUND_HALF_UP,
2986 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
2990 ExtendedContext = Context(
2991 prec=9, rounding=ROUND_HALF_EVEN,
2997 ##### Useful Constants (internal use only) ####################
3000 Inf = Decimal('Inf')
3001 negInf = Decimal('-Inf')
3003 #Infsign[sign] is infinity w/ that sign
3004 Infsign = (Inf, negInf)
3006 NaN = Decimal('NaN')
3009 ##### crud for parsing strings #################################
3012 # There's an optional sign at the start, and an optional exponent
3013 # at the end. The exponent has an optional sign and at least one
3014 # digit. In between, must have either at least one digit followed
3015 # by an optional fraction, or a decimal point followed by at least
3018 _parser = re.compile(r"""
3022 (?P<int>\d+) (\. (?P<frac>\d*))?
3024 \. (?P<onlyfrac>\d+)
3026 ([eE](?P<exp>[-+]? \d+))?
3029 """, re.VERBOSE).match #Uncomment the \s* to allow leading or trailing spaces.
3033 # return sign, n, p s.t. float string value == -1**sign * n * 10**p exactly
3035 def _string2exact(s):
3038 raise ValueError("invalid literal for Decimal: %r" % s)
3040 if m.group('sign') == "-":
3045 exp = m.group('exp')
3051 intpart = m.group('int')
3054 fracpart = m.group('onlyfrac')
3056 fracpart = m.group('frac')
3057 if fracpart is None:
3060 exp -= len(fracpart)
3062 mantissa = intpart + fracpart
3063 tmp = map(int, mantissa)
3065 while tmp and tmp[0] == 0:
3071 return (sign, tuple(backup), exp)
3072 return (sign, (0,), exp)
3073 mantissa = tuple(tmp)
3075 return (sign, mantissa, exp)
3078 if __name__ == '__main__':
3080 doctest.testmod(sys.modules[__name__])
3082 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: