Fix off-by-one error that resulted in missed characters
[pytest.git] / Lib / decimal.py
blobebeb6d72081c5aef34f331e77c8c9712acdd8c0d
1 # Copyright (c) 2004 Python Software Foundation.
2 # All rights reserved.
4 # Written by Eric Price <eprice at tjhsst.edu>
5 # and Facundo Batista <facundo at taniquetil.com.ar>
6 # and Raymond Hettinger <python at rcn.com>
7 # and Aahz <aahz at pobox.com>
8 # and Tim Peters
10 # This module is currently Py2.3 compatible and should be kept that way
11 # unless a major compelling advantage arises. IOW, 2.3 compatibility is
12 # strongly preferred, but not guaranteed.
14 # Also, this module should be kept in sync with the latest updates of
15 # the IBM specification as it evolves. Those updates will be treated
16 # as bug fixes (deviation from the spec is a compatibility, usability
17 # bug) and will be backported. At this point the spec is stabilizing
18 # and the updates are becoming fewer, smaller, and less significant.
20 """
21 This is a Py2.3 implementation of decimal floating point arithmetic based on
22 the General Decimal Arithmetic Specification:
24 www2.hursley.ibm.com/decimal/decarith.html
26 and IEEE standard 854-1987:
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
30 Decimal floating point has finite precision with arbitrarily large bounds.
32 The purpose of this module is to support arithmetic using familiar
33 "schoolhouse" rules and to avoid some of the tricky representation
34 issues associated with binary floating point. The package is especially
35 useful for financial applications or for contexts where users have
36 expectations that are at odds with binary floating point (for instance,
37 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38 of the expected Decimal("0.00") returned by decimal floating point).
40 Here are some examples of using the decimal module:
42 >>> from decimal import *
43 >>> setcontext(ExtendedContext)
44 >>> Decimal(0)
45 Decimal("0")
46 >>> Decimal("1")
47 Decimal("1")
48 >>> Decimal("-.0123")
49 Decimal("-0.0123")
50 >>> Decimal(123456)
51 Decimal("123456")
52 >>> Decimal("123.45e12345678901234567890")
53 Decimal("1.2345E+12345678901234567892")
54 >>> Decimal("1.33") + Decimal("1.27")
55 Decimal("2.60")
56 >>> Decimal("12.34") + Decimal("3.87") - Decimal("18.41")
57 Decimal("-2.20")
58 >>> dig = Decimal(1)
59 >>> print dig / Decimal(3)
60 0.333333333
61 >>> getcontext().prec = 18
62 >>> print dig / Decimal(3)
63 0.333333333333333333
64 >>> print dig.sqrt()
66 >>> print Decimal(3).sqrt()
67 1.73205080756887729
68 >>> print Decimal(3) ** 123
69 4.85192780976896427E+58
70 >>> inf = Decimal(1) / Decimal(0)
71 >>> print inf
72 Infinity
73 >>> neginf = Decimal(-1) / Decimal(0)
74 >>> print neginf
75 -Infinity
76 >>> print neginf + inf
77 NaN
78 >>> print neginf * inf
79 -Infinity
80 >>> print dig / 0
81 Infinity
82 >>> getcontext().traps[DivisionByZero] = 1
83 >>> print dig / 0
84 Traceback (most recent call last):
85 ...
86 ...
87 ...
88 DivisionByZero: x / 0
89 >>> c = Context()
90 >>> c.traps[InvalidOperation] = 0
91 >>> print c.flags[InvalidOperation]
93 >>> c.divide(Decimal(0), Decimal(0))
94 Decimal("NaN")
95 >>> c.traps[InvalidOperation] = 1
96 >>> print c.flags[InvalidOperation]
98 >>> c.flags[InvalidOperation] = 0
99 >>> print c.flags[InvalidOperation]
101 >>> print c.divide(Decimal(0), Decimal(0))
102 Traceback (most recent call last):
106 InvalidOperation: 0 / 0
107 >>> print c.flags[InvalidOperation]
109 >>> c.flags[InvalidOperation] = 0
110 >>> c.traps[InvalidOperation] = 0
111 >>> print c.divide(Decimal(0), Decimal(0))
113 >>> print c.flags[InvalidOperation]
118 __all__ = [
119 # Two major classes
120 'Decimal', 'Context',
122 # Contexts
123 'DefaultContext', 'BasicContext', 'ExtendedContext',
125 # Exceptions
126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
133 # Functions for manipulating contexts
134 'setcontext', 'getcontext', 'localcontext'
137 import copy as _copy
139 # Rounding
140 ROUND_DOWN = 'ROUND_DOWN'
141 ROUND_HALF_UP = 'ROUND_HALF_UP'
142 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
143 ROUND_CEILING = 'ROUND_CEILING'
144 ROUND_FLOOR = 'ROUND_FLOOR'
145 ROUND_UP = 'ROUND_UP'
146 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
147 ROUND_05UP = 'ROUND_05UP'
149 # Errors
151 class DecimalException(ArithmeticError):
152 """Base exception class.
154 Used exceptions derive from this.
155 If an exception derives from another exception besides this (such as
156 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
157 called if the others are present. This isn't actually used for
158 anything, though.
160 handle -- Called when context._raise_error is called and the
161 trap_enabler is set. First argument is self, second is the
162 context. More arguments can be given, those being after
163 the explanation in _raise_error (For example,
164 context._raise_error(NewError, '(-x)!', self._sign) would
165 call NewError().handle(context, self._sign).)
167 To define a new exception, it should be sufficient to have it derive
168 from DecimalException.
170 def handle(self, context, *args):
171 pass
174 class Clamped(DecimalException):
175 """Exponent of a 0 changed to fit bounds.
177 This occurs and signals clamped if the exponent of a result has been
178 altered in order to fit the constraints of a specific concrete
179 representation. This may occur when the exponent of a zero result would
180 be outside the bounds of a representation, or when a large normal
181 number would have an encoded exponent that cannot be represented. In
182 this latter case, the exponent is reduced to fit and the corresponding
183 number of zero digits are appended to the coefficient ("fold-down").
186 class InvalidOperation(DecimalException):
187 """An invalid operation was performed.
189 Various bad things cause this:
191 Something creates a signaling NaN
192 -INF + INF
193 0 * (+-)INF
194 (+-)INF / (+-)INF
195 x % 0
196 (+-)INF % x
197 x._rescale( non-integer )
198 sqrt(-x) , x > 0
199 0 ** 0
200 x ** (non-integer)
201 x ** (+-)INF
202 An operand is invalid
204 The result of the operation after these is a quiet positive NaN,
205 except when the cause is a signaling NaN, in which case the result is
206 also a quiet NaN, but with the original sign, and an optional
207 diagnostic information.
209 def handle(self, context, *args):
210 if args:
211 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
212 return ans._fix_nan(context)
213 return NaN
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].
222 def handle(self, context, *args):
223 return NaN
225 class DivisionByZero(DecimalException, ZeroDivisionError):
226 """Division by 0.
228 This occurs and signals division-by-zero if division of a finite number
229 by zero was attempted (during a divide-integer or divide operation, or a
230 power operation with negative right-hand operand), and the dividend was
231 not zero.
233 The result of the operation is [sign,inf], where sign is the exclusive
234 or of the signs of the operands for divide, or is 1 for an odd power of
235 -0, for power.
238 def handle(self, context, sign, *args):
239 return Infsign[sign]
241 class DivisionImpossible(InvalidOperation):
242 """Cannot perform the division adequately.
244 This occurs and signals invalid-operation if the integer result of a
245 divide-integer or remainder operation had too many digits (would be
246 longer than precision). The result is [0,qNaN].
249 def handle(self, context, *args):
250 return NaN
252 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
253 """Undefined result of division.
255 This occurs and signals invalid-operation if division by zero was
256 attempted (during a divide-integer, divide, or remainder operation), and
257 the dividend is also zero. The result is [0,qNaN].
260 def handle(self, context, *args):
261 return NaN
263 class Inexact(DecimalException):
264 """Had to round, losing information.
266 This occurs and signals inexact whenever the result of an operation is
267 not exact (that is, it needed to be rounded and any discarded digits
268 were non-zero), or if an overflow or underflow condition occurs. The
269 result in all cases is unchanged.
271 The inexact signal may be tested (or trapped) to determine if a given
272 operation (or sequence of operations) was inexact.
275 class InvalidContext(InvalidOperation):
276 """Invalid context. Unknown rounding, for example.
278 This occurs and signals invalid-operation if an invalid context was
279 detected during an operation. This can occur if contexts are not checked
280 on creation and either the precision exceeds the capability of the
281 underlying concrete representation or an unknown or unsupported rounding
282 was specified. These aspects of the context need only be checked when
283 the values are required to be used. The result is [0,qNaN].
286 def handle(self, context, *args):
287 return NaN
289 class Rounded(DecimalException):
290 """Number got rounded (not necessarily changed during rounding).
292 This occurs and signals rounded whenever the result of an operation is
293 rounded (that is, some zero or non-zero digits were discarded from the
294 coefficient), or if an overflow or underflow condition occurs. The
295 result in all cases is unchanged.
297 The rounded signal may be tested (or trapped) to determine if a given
298 operation (or sequence of operations) caused a loss of precision.
301 class Subnormal(DecimalException):
302 """Exponent < Emin before rounding.
304 This occurs and signals subnormal whenever the result of a conversion or
305 operation is subnormal (that is, its adjusted exponent is less than
306 Emin, before any rounding). The result in all cases is unchanged.
308 The subnormal signal may be tested (or trapped) to determine if a given
309 or operation (or sequence of operations) yielded a subnormal result.
312 class Overflow(Inexact, Rounded):
313 """Numerical overflow.
315 This occurs and signals overflow if the adjusted exponent of a result
316 (from a conversion or from an operation that is not an attempt to divide
317 by zero), after rounding, would be greater than the largest value that
318 can be handled by the implementation (the value Emax).
320 The result depends on the rounding mode:
322 For round-half-up and round-half-even (and for round-half-down and
323 round-up, if implemented), the result of the operation is [sign,inf],
324 where sign is the sign of the intermediate result. For round-down, the
325 result is the largest finite number that can be represented in the
326 current precision, with the sign of the intermediate result. For
327 round-ceiling, the result is the same as for round-down if the sign of
328 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
329 the result is the same as for round-down if the sign of the intermediate
330 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
331 will also be raised.
334 def handle(self, context, sign, *args):
335 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
336 ROUND_HALF_DOWN, ROUND_UP):
337 return Infsign[sign]
338 if sign == 0:
339 if context.rounding == ROUND_CEILING:
340 return Infsign[sign]
341 return _dec_from_triple(sign, '9'*context.prec,
342 context.Emax-context.prec+1)
343 if sign == 1:
344 if context.rounding == ROUND_FLOOR:
345 return Infsign[sign]
346 return _dec_from_triple(sign, '9'*context.prec,
347 context.Emax-context.prec+1)
350 class Underflow(Inexact, Rounded, Subnormal):
351 """Numerical underflow with result rounded to 0.
353 This occurs and signals underflow if a result is inexact and the
354 adjusted exponent of the result would be smaller (more negative) than
355 the smallest value that can be handled by the implementation (the value
356 Emin). That is, the result is both inexact and subnormal.
358 The result after an underflow will be a subnormal number rounded, if
359 necessary, so that its exponent is not less than Etiny. This may result
360 in 0 with the sign of the intermediate result and an exponent of Etiny.
362 In all cases, Inexact, Rounded, and Subnormal will also be raised.
365 # List of public traps and flags
366 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
367 Underflow, InvalidOperation, Subnormal]
369 # Map conditions (per the spec) to signals
370 _condition_map = {ConversionSyntax:InvalidOperation,
371 DivisionImpossible:InvalidOperation,
372 DivisionUndefined:InvalidOperation,
373 InvalidContext:InvalidOperation}
375 ##### Context Functions ##################################################
377 # The getcontext() and setcontext() function manage access to a thread-local
378 # current context. Py2.4 offers direct support for thread locals. If that
379 # is not available, use threading.currentThread() which is slower but will
380 # work for older Pythons. If threads are not part of the build, create a
381 # mock threading object with threading.local() returning the module namespace.
383 try:
384 import threading
385 except ImportError:
386 # Python was compiled without threads; create a mock object instead
387 import sys
388 class MockThreading(object):
389 def local(self, sys=sys):
390 return sys.modules[__name__]
391 threading = MockThreading()
392 del sys, MockThreading
394 try:
395 threading.local
397 except AttributeError:
399 # To fix reloading, force it to create a new context
400 # Old contexts have different exceptions in their dicts, making problems.
401 if hasattr(threading.currentThread(), '__decimal_context__'):
402 del threading.currentThread().__decimal_context__
404 def setcontext(context):
405 """Set this thread's context to context."""
406 if context in (DefaultContext, BasicContext, ExtendedContext):
407 context = context.copy()
408 context.clear_flags()
409 threading.currentThread().__decimal_context__ = context
411 def getcontext():
412 """Returns this thread's context.
414 If this thread does not yet have a context, returns
415 a new context and sets this thread's context.
416 New contexts are copies of DefaultContext.
418 try:
419 return threading.currentThread().__decimal_context__
420 except AttributeError:
421 context = Context()
422 threading.currentThread().__decimal_context__ = context
423 return context
425 else:
427 local = threading.local()
428 if hasattr(local, '__decimal_context__'):
429 del local.__decimal_context__
431 def getcontext(_local=local):
432 """Returns this thread's context.
434 If this thread does not yet have a context, returns
435 a new context and sets this thread's context.
436 New contexts are copies of DefaultContext.
438 try:
439 return _local.__decimal_context__
440 except AttributeError:
441 context = Context()
442 _local.__decimal_context__ = context
443 return context
445 def setcontext(context, _local=local):
446 """Set this thread's context to context."""
447 if context in (DefaultContext, BasicContext, ExtendedContext):
448 context = context.copy()
449 context.clear_flags()
450 _local.__decimal_context__ = context
452 del threading, local # Don't contaminate the namespace
454 def localcontext(ctx=None):
455 """Return a context manager for a copy of the supplied context
457 Uses a copy of the current context if no context is specified
458 The returned context manager creates a local decimal context
459 in a with statement:
460 def sin(x):
461 with localcontext() as ctx:
462 ctx.prec += 2
463 # Rest of sin calculation algorithm
464 # uses a precision 2 greater than normal
465 return +s # Convert result to normal precision
467 def sin(x):
468 with localcontext(ExtendedContext):
469 # Rest of sin calculation algorithm
470 # uses the Extended Context from the
471 # General Decimal Arithmetic Specification
472 return +s # Convert result to normal context
475 # The string below can't be included in the docstring until Python 2.6
476 # as the doctest module doesn't understand __future__ statements
478 >>> from __future__ import with_statement
479 >>> print getcontext().prec
481 >>> with localcontext():
482 ... ctx = getcontext()
483 ... ctx.prec += 2
484 ... print ctx.prec
487 >>> with localcontext(ExtendedContext):
488 ... print getcontext().prec
491 >>> print getcontext().prec
494 if ctx is None: ctx = getcontext()
495 return _ContextManager(ctx)
498 ##### Decimal class #######################################################
500 class Decimal(object):
501 """Floating point class for decimal arithmetic."""
503 __slots__ = ('_exp','_int','_sign', '_is_special')
504 # Generally, the value of the Decimal instance is given by
505 # (-1)**_sign * _int * 10**_exp
506 # Special values are signified by _is_special == True
508 # We're immutable, so use __new__ not __init__
509 def __new__(cls, value="0", context=None):
510 """Create a decimal point instance.
512 >>> Decimal('3.14') # string input
513 Decimal("3.14")
514 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
515 Decimal("3.14")
516 >>> Decimal(314) # int or long
517 Decimal("314")
518 >>> Decimal(Decimal(314)) # another decimal instance
519 Decimal("314")
522 # Note that the coefficient, self._int, is actually stored as
523 # a string rather than as a tuple of digits. This speeds up
524 # the "digits to integer" and "integer to digits" conversions
525 # that are used in almost every arithmetic operation on
526 # Decimals. This is an internal detail: the as_tuple function
527 # and the Decimal constructor still deal with tuples of
528 # digits.
530 self = object.__new__(cls)
532 # From a string
533 # REs insist on real strings, so we can too.
534 if isinstance(value, basestring):
535 m = _parser(value)
536 if m is None:
537 if context is None:
538 context = getcontext()
539 return context._raise_error(ConversionSyntax,
540 "Invalid literal for Decimal: %r" % value)
542 if m.group('sign') == "-":
543 self._sign = 1
544 else:
545 self._sign = 0
546 intpart = m.group('int')
547 if intpart is not None:
548 # finite number
549 fracpart = m.group('frac')
550 exp = int(m.group('exp') or '0')
551 if fracpart is not None:
552 self._int = (intpart+fracpart).lstrip('0') or '0'
553 self._exp = exp - len(fracpart)
554 else:
555 self._int = intpart.lstrip('0') or '0'
556 self._exp = exp
557 self._is_special = False
558 else:
559 diag = m.group('diag')
560 if diag is not None:
561 # NaN
562 self._int = diag.lstrip('0')
563 if m.group('signal'):
564 self._exp = 'N'
565 else:
566 self._exp = 'n'
567 else:
568 # infinity
569 self._int = '0'
570 self._exp = 'F'
571 self._is_special = True
572 return self
574 # From an integer
575 if isinstance(value, (int,long)):
576 if value >= 0:
577 self._sign = 0
578 else:
579 self._sign = 1
580 self._exp = 0
581 self._int = str(abs(value))
582 self._is_special = False
583 return self
585 # From another decimal
586 if isinstance(value, Decimal):
587 self._exp = value._exp
588 self._sign = value._sign
589 self._int = value._int
590 self._is_special = value._is_special
591 return self
593 # From an internal working value
594 if isinstance(value, _WorkRep):
595 self._sign = value.sign
596 self._int = str(value.int)
597 self._exp = int(value.exp)
598 self._is_special = False
599 return self
601 # tuple/list conversion (possibly from as_tuple())
602 if isinstance(value, (list,tuple)):
603 if len(value) != 3:
604 raise ValueError('Invalid tuple size in creation of Decimal '
605 'from list or tuple. The list or tuple '
606 'should have exactly three elements.')
607 # process sign. The isinstance test rejects floats
608 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
609 raise ValueError("Invalid sign. The first value in the tuple "
610 "should be an integer; either 0 for a "
611 "positive number or 1 for a negative number.")
612 self._sign = value[0]
613 if value[2] == 'F':
614 # infinity: value[1] is ignored
615 self._int = '0'
616 self._exp = value[2]
617 self._is_special = True
618 else:
619 # process and validate the digits in value[1]
620 digits = []
621 for digit in value[1]:
622 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
623 # skip leading zeros
624 if digits or digit != 0:
625 digits.append(digit)
626 else:
627 raise ValueError("The second value in the tuple must "
628 "be composed of integers in the range "
629 "0 through 9.")
630 if value[2] in ('n', 'N'):
631 # NaN: digits form the diagnostic
632 self._int = ''.join(map(str, digits))
633 self._exp = value[2]
634 self._is_special = True
635 elif isinstance(value[2], (int, long)):
636 # finite number: digits give the coefficient
637 self._int = ''.join(map(str, digits or [0]))
638 self._exp = value[2]
639 self._is_special = False
640 else:
641 raise ValueError("The third value in the tuple must "
642 "be an integer, or one of the "
643 "strings 'F', 'n', 'N'.")
644 return self
646 if isinstance(value, float):
647 raise TypeError("Cannot convert float to Decimal. " +
648 "First convert the float to a string")
650 raise TypeError("Cannot convert %r to Decimal" % value)
652 def _isnan(self):
653 """Returns whether the number is not actually one.
655 0 if a number
656 1 if NaN
657 2 if sNaN
659 if self._is_special:
660 exp = self._exp
661 if exp == 'n':
662 return 1
663 elif exp == 'N':
664 return 2
665 return 0
667 def _isinfinity(self):
668 """Returns whether the number is infinite
670 0 if finite or not a number
671 1 if +INF
672 -1 if -INF
674 if self._exp == 'F':
675 if self._sign:
676 return -1
677 return 1
678 return 0
680 def _check_nans(self, other=None, context=None):
681 """Returns whether the number is not actually one.
683 if self, other are sNaN, signal
684 if self, other are NaN return nan
685 return 0
687 Done before operations.
690 self_is_nan = self._isnan()
691 if other is None:
692 other_is_nan = False
693 else:
694 other_is_nan = other._isnan()
696 if self_is_nan or other_is_nan:
697 if context is None:
698 context = getcontext()
700 if self_is_nan == 2:
701 return context._raise_error(InvalidOperation, 'sNaN',
702 self)
703 if other_is_nan == 2:
704 return context._raise_error(InvalidOperation, 'sNaN',
705 other)
706 if self_is_nan:
707 return self._fix_nan(context)
709 return other._fix_nan(context)
710 return 0
712 def __nonzero__(self):
713 """Return True if self is nonzero; otherwise return False.
715 NaNs and infinities are considered nonzero.
717 return self._is_special or self._int != '0'
719 def __cmp__(self, other):
720 other = _convert_other(other)
721 if other is NotImplemented:
722 # Never return NotImplemented
723 return 1
725 if self._is_special or other._is_special:
726 # check for nans, without raising on a signaling nan
727 if self._isnan() or other._isnan():
728 return 1 # Comparison involving NaN's always reports self > other
730 # INF = INF
731 return cmp(self._isinfinity(), other._isinfinity())
733 # check for zeros; note that cmp(0, -0) should return 0
734 if not self:
735 if not other:
736 return 0
737 else:
738 return -((-1)**other._sign)
739 if not other:
740 return (-1)**self._sign
742 # If different signs, neg one is less
743 if other._sign < self._sign:
744 return -1
745 if self._sign < other._sign:
746 return 1
748 self_adjusted = self.adjusted()
749 other_adjusted = other.adjusted()
750 if self_adjusted == other_adjusted:
751 self_padded = self._int + '0'*(self._exp - other._exp)
752 other_padded = other._int + '0'*(other._exp - self._exp)
753 return cmp(self_padded, other_padded) * (-1)**self._sign
754 elif self_adjusted > other_adjusted:
755 return (-1)**self._sign
756 else: # self_adjusted < other_adjusted
757 return -((-1)**self._sign)
759 def __eq__(self, other):
760 if not isinstance(other, (Decimal, int, long)):
761 return NotImplemented
762 return self.__cmp__(other) == 0
764 def __ne__(self, other):
765 if not isinstance(other, (Decimal, int, long)):
766 return NotImplemented
767 return self.__cmp__(other) != 0
769 def compare(self, other, context=None):
770 """Compares one to another.
772 -1 => a < b
773 0 => a = b
774 1 => a > b
775 NaN => one is NaN
776 Like __cmp__, but returns Decimal instances.
778 other = _convert_other(other, raiseit=True)
780 # Compare(NaN, NaN) = NaN
781 if (self._is_special or other and other._is_special):
782 ans = self._check_nans(other, context)
783 if ans:
784 return ans
786 return Decimal(self.__cmp__(other))
788 def __hash__(self):
789 """x.__hash__() <==> hash(x)"""
790 # Decimal integers must hash the same as the ints
792 # The hash of a nonspecial noninteger Decimal must depend only
793 # on the value of that Decimal, and not on its representation.
794 # For example: hash(Decimal("100E-1")) == hash(Decimal("10")).
795 if self._is_special:
796 if self._isnan():
797 raise TypeError('Cannot hash a NaN value.')
798 return hash(str(self))
799 if not self:
800 return 0
801 if self._isinteger():
802 op = _WorkRep(self.to_integral_value())
803 return hash((-1)**op.sign*op.int*10**op.exp)
804 # The value of a nonzero nonspecial Decimal instance is
805 # faithfully represented by the triple consisting of its sign,
806 # its adjusted exponent, and its coefficient with trailing
807 # zeros removed.
808 return hash((self._sign,
809 self._exp+len(self._int),
810 self._int.rstrip('0')))
812 def as_tuple(self):
813 """Represents the number as a triple tuple.
815 To show the internals exactly as they are.
817 return (self._sign, tuple(map(int, self._int)), self._exp)
819 def __repr__(self):
820 """Represents the number as an instance of Decimal."""
821 # Invariant: eval(repr(d)) == d
822 return 'Decimal("%s")' % str(self)
824 def __str__(self, eng=False, context=None):
825 """Return string representation of the number in scientific notation.
827 Captures all of the information in the underlying representation.
830 sign = ['', '-'][self._sign]
831 if self._is_special:
832 if self._exp == 'F':
833 return sign + 'Infinity'
834 elif self._exp == 'n':
835 return sign + 'NaN' + self._int
836 else: # self._exp == 'N'
837 return sign + 'sNaN' + self._int
839 # number of digits of self._int to left of decimal point
840 leftdigits = self._exp + len(self._int)
842 # dotplace is number of digits of self._int to the left of the
843 # decimal point in the mantissa of the output string (that is,
844 # after adjusting the exponent)
845 if self._exp <= 0 and leftdigits > -6:
846 # no exponent required
847 dotplace = leftdigits
848 elif not eng:
849 # usual scientific notation: 1 digit on left of the point
850 dotplace = 1
851 elif self._int == '0':
852 # engineering notation, zero
853 dotplace = (leftdigits + 1) % 3 - 1
854 else:
855 # engineering notation, nonzero
856 dotplace = (leftdigits - 1) % 3 + 1
858 if dotplace <= 0:
859 intpart = '0'
860 fracpart = '.' + '0'*(-dotplace) + self._int
861 elif dotplace >= len(self._int):
862 intpart = self._int+'0'*(dotplace-len(self._int))
863 fracpart = ''
864 else:
865 intpart = self._int[:dotplace]
866 fracpart = '.' + self._int[dotplace:]
867 if leftdigits == dotplace:
868 exp = ''
869 else:
870 if context is None:
871 context = getcontext()
872 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
874 return sign + intpart + fracpart + exp
876 def to_eng_string(self, context=None):
877 """Convert to engineering-type string.
879 Engineering notation has an exponent which is a multiple of 3, so there
880 are up to 3 digits left of the decimal place.
882 Same rules for when in exponential and when as a value as in __str__.
884 return self.__str__(eng=True, context=context)
886 def __neg__(self, context=None):
887 """Returns a copy with the sign switched.
889 Rounds, if it has reason.
891 if self._is_special:
892 ans = self._check_nans(context=context)
893 if ans:
894 return ans
896 if not self:
897 # -Decimal('0') is Decimal('0'), not Decimal('-0')
898 ans = self.copy_abs()
899 else:
900 ans = self.copy_negate()
902 if context is None:
903 context = getcontext()
904 return ans._fix(context)
906 def __pos__(self, context=None):
907 """Returns a copy, unless it is a sNaN.
909 Rounds the number (if more then precision digits)
911 if self._is_special:
912 ans = self._check_nans(context=context)
913 if ans:
914 return ans
916 if not self:
917 # + (-0) = 0
918 ans = self.copy_abs()
919 else:
920 ans = Decimal(self)
922 if context is None:
923 context = getcontext()
924 return ans._fix(context)
926 def __abs__(self, round=True, context=None):
927 """Returns the absolute value of self.
929 If the keyword argument 'round' is false, do not round. The
930 expression self.__abs__(round=False) is equivalent to
931 self.copy_abs().
933 if not round:
934 return self.copy_abs()
936 if self._is_special:
937 ans = self._check_nans(context=context)
938 if ans:
939 return ans
941 if self._sign:
942 ans = self.__neg__(context=context)
943 else:
944 ans = self.__pos__(context=context)
946 return ans
948 def __add__(self, other, context=None):
949 """Returns self + other.
951 -INF + INF (or the reverse) cause InvalidOperation errors.
953 other = _convert_other(other)
954 if other is NotImplemented:
955 return other
957 if context is None:
958 context = getcontext()
960 if self._is_special or other._is_special:
961 ans = self._check_nans(other, context)
962 if ans:
963 return ans
965 if self._isinfinity():
966 # If both INF, same sign => same as both, opposite => error.
967 if self._sign != other._sign and other._isinfinity():
968 return context._raise_error(InvalidOperation, '-INF + INF')
969 return Decimal(self)
970 if other._isinfinity():
971 return Decimal(other) # Can't both be infinity here
973 exp = min(self._exp, other._exp)
974 negativezero = 0
975 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
976 # If the answer is 0, the sign should be negative, in this case.
977 negativezero = 1
979 if not self and not other:
980 sign = min(self._sign, other._sign)
981 if negativezero:
982 sign = 1
983 ans = _dec_from_triple(sign, '0', exp)
984 ans = ans._fix(context)
985 return ans
986 if not self:
987 exp = max(exp, other._exp - context.prec-1)
988 ans = other._rescale(exp, context.rounding)
989 ans = ans._fix(context)
990 return ans
991 if not other:
992 exp = max(exp, self._exp - context.prec-1)
993 ans = self._rescale(exp, context.rounding)
994 ans = ans._fix(context)
995 return ans
997 op1 = _WorkRep(self)
998 op2 = _WorkRep(other)
999 op1, op2 = _normalize(op1, op2, context.prec)
1001 result = _WorkRep()
1002 if op1.sign != op2.sign:
1003 # Equal and opposite
1004 if op1.int == op2.int:
1005 ans = _dec_from_triple(negativezero, '0', exp)
1006 ans = ans._fix(context)
1007 return ans
1008 if op1.int < op2.int:
1009 op1, op2 = op2, op1
1010 # OK, now abs(op1) > abs(op2)
1011 if op1.sign == 1:
1012 result.sign = 1
1013 op1.sign, op2.sign = op2.sign, op1.sign
1014 else:
1015 result.sign = 0
1016 # So we know the sign, and op1 > 0.
1017 elif op1.sign == 1:
1018 result.sign = 1
1019 op1.sign, op2.sign = (0, 0)
1020 else:
1021 result.sign = 0
1022 # Now, op1 > abs(op2) > 0
1024 if op2.sign == 0:
1025 result.int = op1.int + op2.int
1026 else:
1027 result.int = op1.int - op2.int
1029 result.exp = op1.exp
1030 ans = Decimal(result)
1031 ans = ans._fix(context)
1032 return ans
1034 __radd__ = __add__
1036 def __sub__(self, other, context=None):
1037 """Return self - other"""
1038 other = _convert_other(other)
1039 if other is NotImplemented:
1040 return other
1042 if self._is_special or other._is_special:
1043 ans = self._check_nans(other, context=context)
1044 if ans:
1045 return ans
1047 # self - other is computed as self + other.copy_negate()
1048 return self.__add__(other.copy_negate(), context=context)
1050 def __rsub__(self, other, context=None):
1051 """Return other - self"""
1052 other = _convert_other(other)
1053 if other is NotImplemented:
1054 return other
1056 return other.__sub__(self, context=context)
1058 def __mul__(self, other, context=None):
1059 """Return self * other.
1061 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1063 other = _convert_other(other)
1064 if other is NotImplemented:
1065 return other
1067 if context is None:
1068 context = getcontext()
1070 resultsign = self._sign ^ other._sign
1072 if self._is_special or other._is_special:
1073 ans = self._check_nans(other, context)
1074 if ans:
1075 return ans
1077 if self._isinfinity():
1078 if not other:
1079 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1080 return Infsign[resultsign]
1082 if other._isinfinity():
1083 if not self:
1084 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1085 return Infsign[resultsign]
1087 resultexp = self._exp + other._exp
1089 # Special case for multiplying by zero
1090 if not self or not other:
1091 ans = _dec_from_triple(resultsign, '0', resultexp)
1092 # Fixing in case the exponent is out of bounds
1093 ans = ans._fix(context)
1094 return ans
1096 # Special case for multiplying by power of 10
1097 if self._int == '1':
1098 ans = _dec_from_triple(resultsign, other._int, resultexp)
1099 ans = ans._fix(context)
1100 return ans
1101 if other._int == '1':
1102 ans = _dec_from_triple(resultsign, self._int, resultexp)
1103 ans = ans._fix(context)
1104 return ans
1106 op1 = _WorkRep(self)
1107 op2 = _WorkRep(other)
1109 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1110 ans = ans._fix(context)
1112 return ans
1113 __rmul__ = __mul__
1115 def __div__(self, other, context=None):
1116 """Return self / other."""
1117 other = _convert_other(other)
1118 if other is NotImplemented:
1119 return NotImplemented
1121 if context is None:
1122 context = getcontext()
1124 sign = self._sign ^ other._sign
1126 if self._is_special or other._is_special:
1127 ans = self._check_nans(other, context)
1128 if ans:
1129 return ans
1131 if self._isinfinity() and other._isinfinity():
1132 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1134 if self._isinfinity():
1135 return Infsign[sign]
1137 if other._isinfinity():
1138 context._raise_error(Clamped, 'Division by infinity')
1139 return _dec_from_triple(sign, '0', context.Etiny())
1141 # Special cases for zeroes
1142 if not other:
1143 if not self:
1144 return context._raise_error(DivisionUndefined, '0 / 0')
1145 return context._raise_error(DivisionByZero, 'x / 0', sign)
1147 if not self:
1148 exp = self._exp - other._exp
1149 coeff = 0
1150 else:
1151 # OK, so neither = 0, INF or NaN
1152 shift = len(other._int) - len(self._int) + context.prec + 1
1153 exp = self._exp - other._exp - shift
1154 op1 = _WorkRep(self)
1155 op2 = _WorkRep(other)
1156 if shift >= 0:
1157 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1158 else:
1159 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1160 if remainder:
1161 # result is not exact; adjust to ensure correct rounding
1162 if coeff % 5 == 0:
1163 coeff += 1
1164 else:
1165 # result is exact; get as close to ideal exponent as possible
1166 ideal_exp = self._exp - other._exp
1167 while exp < ideal_exp and coeff % 10 == 0:
1168 coeff //= 10
1169 exp += 1
1171 ans = _dec_from_triple(sign, str(coeff), exp)
1172 return ans._fix(context)
1174 __truediv__ = __div__
1176 def _divide(self, other, context):
1177 """Return (self // other, self % other), to context.prec precision.
1179 Assumes that neither self nor other is a NaN, that self is not
1180 infinite and that other is nonzero.
1182 sign = self._sign ^ other._sign
1183 if other._isinfinity():
1184 ideal_exp = self._exp
1185 else:
1186 ideal_exp = min(self._exp, other._exp)
1188 expdiff = self.adjusted() - other.adjusted()
1189 if not self or other._isinfinity() or expdiff <= -2:
1190 return (_dec_from_triple(sign, '0', 0),
1191 self._rescale(ideal_exp, context.rounding))
1192 if expdiff <= context.prec:
1193 op1 = _WorkRep(self)
1194 op2 = _WorkRep(other)
1195 if op1.exp >= op2.exp:
1196 op1.int *= 10**(op1.exp - op2.exp)
1197 else:
1198 op2.int *= 10**(op2.exp - op1.exp)
1199 q, r = divmod(op1.int, op2.int)
1200 if q < 10**context.prec:
1201 return (_dec_from_triple(sign, str(q), 0),
1202 _dec_from_triple(self._sign, str(r), ideal_exp))
1204 # Here the quotient is too large to be representable
1205 ans = context._raise_error(DivisionImpossible,
1206 'quotient too large in //, % or divmod')
1207 return ans, ans
1209 def __rdiv__(self, other, context=None):
1210 """Swaps self/other and returns __div__."""
1211 other = _convert_other(other)
1212 if other is NotImplemented:
1213 return other
1214 return other.__div__(self, context=context)
1215 __rtruediv__ = __rdiv__
1217 def __divmod__(self, other, context=None):
1219 Return (self // other, self % other)
1221 other = _convert_other(other)
1222 if other is NotImplemented:
1223 return other
1225 if context is None:
1226 context = getcontext()
1228 ans = self._check_nans(other, context)
1229 if ans:
1230 return (ans, ans)
1232 sign = self._sign ^ other._sign
1233 if self._isinfinity():
1234 if other._isinfinity():
1235 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1236 return ans, ans
1237 else:
1238 return (Infsign[sign],
1239 context._raise_error(InvalidOperation, 'INF % x'))
1241 if not other:
1242 if not self:
1243 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1244 return ans, ans
1245 else:
1246 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1247 context._raise_error(InvalidOperation, 'x % 0'))
1249 quotient, remainder = self._divide(other, context)
1250 remainder = remainder._fix(context)
1251 return quotient, remainder
1253 def __rdivmod__(self, other, context=None):
1254 """Swaps self/other and returns __divmod__."""
1255 other = _convert_other(other)
1256 if other is NotImplemented:
1257 return other
1258 return other.__divmod__(self, context=context)
1260 def __mod__(self, other, context=None):
1262 self % other
1264 other = _convert_other(other)
1265 if other is NotImplemented:
1266 return other
1268 if context is None:
1269 context = getcontext()
1271 ans = self._check_nans(other, context)
1272 if ans:
1273 return ans
1275 if self._isinfinity():
1276 return context._raise_error(InvalidOperation, 'INF % x')
1277 elif not other:
1278 if self:
1279 return context._raise_error(InvalidOperation, 'x % 0')
1280 else:
1281 return context._raise_error(DivisionUndefined, '0 % 0')
1283 remainder = self._divide(other, context)[1]
1284 remainder = remainder._fix(context)
1285 return remainder
1287 def __rmod__(self, other, context=None):
1288 """Swaps self/other and returns __mod__."""
1289 other = _convert_other(other)
1290 if other is NotImplemented:
1291 return other
1292 return other.__mod__(self, context=context)
1294 def remainder_near(self, other, context=None):
1296 Remainder nearest to 0- abs(remainder-near) <= other/2
1298 if context is None:
1299 context = getcontext()
1301 other = _convert_other(other, raiseit=True)
1303 ans = self._check_nans(other, context)
1304 if ans:
1305 return ans
1307 # self == +/-infinity -> InvalidOperation
1308 if self._isinfinity():
1309 return context._raise_error(InvalidOperation,
1310 'remainder_near(infinity, x)')
1312 # other == 0 -> either InvalidOperation or DivisionUndefined
1313 if not other:
1314 if self:
1315 return context._raise_error(InvalidOperation,
1316 'remainder_near(x, 0)')
1317 else:
1318 return context._raise_error(DivisionUndefined,
1319 'remainder_near(0, 0)')
1321 # other = +/-infinity -> remainder = self
1322 if other._isinfinity():
1323 ans = Decimal(self)
1324 return ans._fix(context)
1326 # self = 0 -> remainder = self, with ideal exponent
1327 ideal_exponent = min(self._exp, other._exp)
1328 if not self:
1329 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1330 return ans._fix(context)
1332 # catch most cases of large or small quotient
1333 expdiff = self.adjusted() - other.adjusted()
1334 if expdiff >= context.prec + 1:
1335 # expdiff >= prec+1 => abs(self/other) > 10**prec
1336 return context._raise_error(DivisionImpossible)
1337 if expdiff <= -2:
1338 # expdiff <= -2 => abs(self/other) < 0.1
1339 ans = self._rescale(ideal_exponent, context.rounding)
1340 return ans._fix(context)
1342 # adjust both arguments to have the same exponent, then divide
1343 op1 = _WorkRep(self)
1344 op2 = _WorkRep(other)
1345 if op1.exp >= op2.exp:
1346 op1.int *= 10**(op1.exp - op2.exp)
1347 else:
1348 op2.int *= 10**(op2.exp - op1.exp)
1349 q, r = divmod(op1.int, op2.int)
1350 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1351 # 10**ideal_exponent. Apply correction to ensure that
1352 # abs(remainder) <= abs(other)/2
1353 if 2*r + (q&1) > op2.int:
1354 r -= op2.int
1355 q += 1
1357 if q >= 10**context.prec:
1358 return context._raise_error(DivisionImpossible)
1360 # result has same sign as self unless r is negative
1361 sign = self._sign
1362 if r < 0:
1363 sign = 1-sign
1364 r = -r
1366 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1367 return ans._fix(context)
1369 def __floordiv__(self, other, context=None):
1370 """self // other"""
1371 other = _convert_other(other)
1372 if other is NotImplemented:
1373 return other
1375 if context is None:
1376 context = getcontext()
1378 ans = self._check_nans(other, context)
1379 if ans:
1380 return ans
1382 if self._isinfinity():
1383 if other._isinfinity():
1384 return context._raise_error(InvalidOperation, 'INF // INF')
1385 else:
1386 return Infsign[self._sign ^ other._sign]
1388 if not other:
1389 if self:
1390 return context._raise_error(DivisionByZero, 'x // 0',
1391 self._sign ^ other._sign)
1392 else:
1393 return context._raise_error(DivisionUndefined, '0 // 0')
1395 return self._divide(other, context)[0]
1397 def __rfloordiv__(self, other, context=None):
1398 """Swaps self/other and returns __floordiv__."""
1399 other = _convert_other(other)
1400 if other is NotImplemented:
1401 return other
1402 return other.__floordiv__(self, context=context)
1404 def __float__(self):
1405 """Float representation."""
1406 return float(str(self))
1408 def __int__(self):
1409 """Converts self to an int, truncating if necessary."""
1410 if self._is_special:
1411 if self._isnan():
1412 context = getcontext()
1413 return context._raise_error(InvalidContext)
1414 elif self._isinfinity():
1415 raise OverflowError("Cannot convert infinity to long")
1416 s = (-1)**self._sign
1417 if self._exp >= 0:
1418 return s*int(self._int)*10**self._exp
1419 else:
1420 return s*int(self._int[:self._exp] or '0')
1422 def __long__(self):
1423 """Converts to a long.
1425 Equivalent to long(int(self))
1427 return long(self.__int__())
1429 def _fix_nan(self, context):
1430 """Decapitate the payload of a NaN to fit the context"""
1431 payload = self._int
1433 # maximum length of payload is precision if _clamp=0,
1434 # precision-1 if _clamp=1.
1435 max_payload_len = context.prec - context._clamp
1436 if len(payload) > max_payload_len:
1437 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1438 return _dec_from_triple(self._sign, payload, self._exp, True)
1439 return Decimal(self)
1441 def _fix(self, context):
1442 """Round if it is necessary to keep self within prec precision.
1444 Rounds and fixes the exponent. Does not raise on a sNaN.
1446 Arguments:
1447 self - Decimal instance
1448 context - context used.
1451 if self._is_special:
1452 if self._isnan():
1453 # decapitate payload if necessary
1454 return self._fix_nan(context)
1455 else:
1456 # self is +/-Infinity; return unaltered
1457 return Decimal(self)
1459 # if self is zero then exponent should be between Etiny and
1460 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1461 Etiny = context.Etiny()
1462 Etop = context.Etop()
1463 if not self:
1464 exp_max = [context.Emax, Etop][context._clamp]
1465 new_exp = min(max(self._exp, Etiny), exp_max)
1466 if new_exp != self._exp:
1467 context._raise_error(Clamped)
1468 return _dec_from_triple(self._sign, '0', new_exp)
1469 else:
1470 return Decimal(self)
1472 # exp_min is the smallest allowable exponent of the result,
1473 # equal to max(self.adjusted()-context.prec+1, Etiny)
1474 exp_min = len(self._int) + self._exp - context.prec
1475 if exp_min > Etop:
1476 # overflow: exp_min > Etop iff self.adjusted() > Emax
1477 context._raise_error(Inexact)
1478 context._raise_error(Rounded)
1479 return context._raise_error(Overflow, 'above Emax', self._sign)
1480 self_is_subnormal = exp_min < Etiny
1481 if self_is_subnormal:
1482 context._raise_error(Subnormal)
1483 exp_min = Etiny
1485 # round if self has too many digits
1486 if self._exp < exp_min:
1487 context._raise_error(Rounded)
1488 digits = len(self._int) + self._exp - exp_min
1489 if digits < 0:
1490 self = _dec_from_triple(self._sign, '1', exp_min-1)
1491 digits = 0
1492 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1493 changed = this_function(digits)
1494 coeff = self._int[:digits] or '0'
1495 if changed == 1:
1496 coeff = str(int(coeff)+1)
1497 ans = _dec_from_triple(self._sign, coeff, exp_min)
1499 if changed:
1500 context._raise_error(Inexact)
1501 if self_is_subnormal:
1502 context._raise_error(Underflow)
1503 if not ans:
1504 # raise Clamped on underflow to 0
1505 context._raise_error(Clamped)
1506 elif len(ans._int) == context.prec+1:
1507 # we get here only if rescaling rounds the
1508 # cofficient up to exactly 10**context.prec
1509 if ans._exp < Etop:
1510 ans = _dec_from_triple(ans._sign,
1511 ans._int[:-1], ans._exp+1)
1512 else:
1513 # Inexact and Rounded have already been raised
1514 ans = context._raise_error(Overflow, 'above Emax',
1515 self._sign)
1516 return ans
1518 # fold down if _clamp == 1 and self has too few digits
1519 if context._clamp == 1 and self._exp > Etop:
1520 context._raise_error(Clamped)
1521 self_padded = self._int + '0'*(self._exp - Etop)
1522 return _dec_from_triple(self._sign, self_padded, Etop)
1524 # here self was representable to begin with; return unchanged
1525 return Decimal(self)
1527 _pick_rounding_function = {}
1529 # for each of the rounding functions below:
1530 # self is a finite, nonzero Decimal
1531 # prec is an integer satisfying 0 <= prec < len(self._int)
1533 # each function returns either -1, 0, or 1, as follows:
1534 # 1 indicates that self should be rounded up (away from zero)
1535 # 0 indicates that self should be truncated, and that all the
1536 # digits to be truncated are zeros (so the value is unchanged)
1537 # -1 indicates that there are nonzero digits to be truncated
1539 def _round_down(self, prec):
1540 """Also known as round-towards-0, truncate."""
1541 if _all_zeros(self._int, prec):
1542 return 0
1543 else:
1544 return -1
1546 def _round_up(self, prec):
1547 """Rounds away from 0."""
1548 return -self._round_down(prec)
1550 def _round_half_up(self, prec):
1551 """Rounds 5 up (away from 0)"""
1552 if self._int[prec] in '56789':
1553 return 1
1554 elif _all_zeros(self._int, prec):
1555 return 0
1556 else:
1557 return -1
1559 def _round_half_down(self, prec):
1560 """Round 5 down"""
1561 if _exact_half(self._int, prec):
1562 return -1
1563 else:
1564 return self._round_half_up(prec)
1566 def _round_half_even(self, prec):
1567 """Round 5 to even, rest to nearest."""
1568 if _exact_half(self._int, prec) and \
1569 (prec == 0 or self._int[prec-1] in '02468'):
1570 return -1
1571 else:
1572 return self._round_half_up(prec)
1574 def _round_ceiling(self, prec):
1575 """Rounds up (not away from 0 if negative.)"""
1576 if self._sign:
1577 return self._round_down(prec)
1578 else:
1579 return -self._round_down(prec)
1581 def _round_floor(self, prec):
1582 """Rounds down (not towards 0 if negative)"""
1583 if not self._sign:
1584 return self._round_down(prec)
1585 else:
1586 return -self._round_down(prec)
1588 def _round_05up(self, prec):
1589 """Round down unless digit prec-1 is 0 or 5."""
1590 if prec and self._int[prec-1] not in '05':
1591 return self._round_down(prec)
1592 else:
1593 return -self._round_down(prec)
1595 def fma(self, other, third, context=None):
1596 """Fused multiply-add.
1598 Returns self*other+third with no rounding of the intermediate
1599 product self*other.
1601 self and other are multiplied together, with no rounding of
1602 the result. The third operand is then added to the result,
1603 and a single final rounding is performed.
1606 other = _convert_other(other, raiseit=True)
1608 # compute product; raise InvalidOperation if either operand is
1609 # a signaling NaN or if the product is zero times infinity.
1610 if self._is_special or other._is_special:
1611 if context is None:
1612 context = getcontext()
1613 if self._exp == 'N':
1614 return context._raise_error(InvalidOperation, 'sNaN', self)
1615 if other._exp == 'N':
1616 return context._raise_error(InvalidOperation, 'sNaN', other)
1617 if self._exp == 'n':
1618 product = self
1619 elif other._exp == 'n':
1620 product = other
1621 elif self._exp == 'F':
1622 if not other:
1623 return context._raise_error(InvalidOperation,
1624 'INF * 0 in fma')
1625 product = Infsign[self._sign ^ other._sign]
1626 elif other._exp == 'F':
1627 if not self:
1628 return context._raise_error(InvalidOperation,
1629 '0 * INF in fma')
1630 product = Infsign[self._sign ^ other._sign]
1631 else:
1632 product = _dec_from_triple(self._sign ^ other._sign,
1633 str(int(self._int) * int(other._int)),
1634 self._exp + other._exp)
1636 third = _convert_other(third, raiseit=True)
1637 return product.__add__(third, context)
1639 def _power_modulo(self, other, modulo, context=None):
1640 """Three argument version of __pow__"""
1642 # if can't convert other and modulo to Decimal, raise
1643 # TypeError; there's no point returning NotImplemented (no
1644 # equivalent of __rpow__ for three argument pow)
1645 other = _convert_other(other, raiseit=True)
1646 modulo = _convert_other(modulo, raiseit=True)
1648 if context is None:
1649 context = getcontext()
1651 # deal with NaNs: if there are any sNaNs then first one wins,
1652 # (i.e. behaviour for NaNs is identical to that of fma)
1653 self_is_nan = self._isnan()
1654 other_is_nan = other._isnan()
1655 modulo_is_nan = modulo._isnan()
1656 if self_is_nan or other_is_nan or modulo_is_nan:
1657 if self_is_nan == 2:
1658 return context._raise_error(InvalidOperation, 'sNaN',
1659 self)
1660 if other_is_nan == 2:
1661 return context._raise_error(InvalidOperation, 'sNaN',
1662 other)
1663 if modulo_is_nan == 2:
1664 return context._raise_error(InvalidOperation, 'sNaN',
1665 modulo)
1666 if self_is_nan:
1667 return self._fix_nan(context)
1668 if other_is_nan:
1669 return other._fix_nan(context)
1670 return modulo._fix_nan(context)
1672 # check inputs: we apply same restrictions as Python's pow()
1673 if not (self._isinteger() and
1674 other._isinteger() and
1675 modulo._isinteger()):
1676 return context._raise_error(InvalidOperation,
1677 'pow() 3rd argument not allowed '
1678 'unless all arguments are integers')
1679 if other < 0:
1680 return context._raise_error(InvalidOperation,
1681 'pow() 2nd argument cannot be '
1682 'negative when 3rd argument specified')
1683 if not modulo:
1684 return context._raise_error(InvalidOperation,
1685 'pow() 3rd argument cannot be 0')
1687 # additional restriction for decimal: the modulus must be less
1688 # than 10**prec in absolute value
1689 if modulo.adjusted() >= context.prec:
1690 return context._raise_error(InvalidOperation,
1691 'insufficient precision: pow() 3rd '
1692 'argument must not have more than '
1693 'precision digits')
1695 # define 0**0 == NaN, for consistency with two-argument pow
1696 # (even though it hurts!)
1697 if not other and not self:
1698 return context._raise_error(InvalidOperation,
1699 'at least one of pow() 1st argument '
1700 'and 2nd argument must be nonzero ;'
1701 '0**0 is not defined')
1703 # compute sign of result
1704 if other._iseven():
1705 sign = 0
1706 else:
1707 sign = self._sign
1709 # convert modulo to a Python integer, and self and other to
1710 # Decimal integers (i.e. force their exponents to be >= 0)
1711 modulo = abs(int(modulo))
1712 base = _WorkRep(self.to_integral_value())
1713 exponent = _WorkRep(other.to_integral_value())
1715 # compute result using integer pow()
1716 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1717 for i in xrange(exponent.exp):
1718 base = pow(base, 10, modulo)
1719 base = pow(base, exponent.int, modulo)
1721 return _dec_from_triple(sign, str(base), 0)
1723 def _power_exact(self, other, p):
1724 """Attempt to compute self**other exactly.
1726 Given Decimals self and other and an integer p, attempt to
1727 compute an exact result for the power self**other, with p
1728 digits of precision. Return None if self**other is not
1729 exactly representable in p digits.
1731 Assumes that elimination of special cases has already been
1732 performed: self and other must both be nonspecial; self must
1733 be positive and not numerically equal to 1; other must be
1734 nonzero. For efficiency, other._exp should not be too large,
1735 so that 10**abs(other._exp) is a feasible calculation."""
1737 # In the comments below, we write x for the value of self and
1738 # y for the value of other. Write x = xc*10**xe and y =
1739 # yc*10**ye.
1741 # The main purpose of this method is to identify the *failure*
1742 # of x**y to be exactly representable with as little effort as
1743 # possible. So we look for cheap and easy tests that
1744 # eliminate the possibility of x**y being exact. Only if all
1745 # these tests are passed do we go on to actually compute x**y.
1747 # Here's the main idea. First normalize both x and y. We
1748 # express y as a rational m/n, with m and n relatively prime
1749 # and n>0. Then for x**y to be exactly representable (at
1750 # *any* precision), xc must be the nth power of a positive
1751 # integer and xe must be divisible by n. If m is negative
1752 # then additionally xc must be a power of either 2 or 5, hence
1753 # a power of 2**n or 5**n.
1755 # There's a limit to how small |y| can be: if y=m/n as above
1756 # then:
1758 # (1) if xc != 1 then for the result to be representable we
1759 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1760 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1761 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1762 # representable.
1764 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1765 # |y| < 1/|xe| then the result is not representable.
1767 # Note that since x is not equal to 1, at least one of (1) and
1768 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1769 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1771 # There's also a limit to how large y can be, at least if it's
1772 # positive: the normalized result will have coefficient xc**y,
1773 # so if it's representable then xc**y < 10**p, and y <
1774 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1775 # not exactly representable.
1777 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1778 # so |y| < 1/xe and the result is not representable.
1779 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1780 # < 1/nbits(xc).
1782 x = _WorkRep(self)
1783 xc, xe = x.int, x.exp
1784 while xc % 10 == 0:
1785 xc //= 10
1786 xe += 1
1788 y = _WorkRep(other)
1789 yc, ye = y.int, y.exp
1790 while yc % 10 == 0:
1791 yc //= 10
1792 ye += 1
1794 # case where xc == 1: result is 10**(xe*y), with xe*y
1795 # required to be an integer
1796 if xc == 1:
1797 if ye >= 0:
1798 exponent = xe*yc*10**ye
1799 else:
1800 exponent, remainder = divmod(xe*yc, 10**-ye)
1801 if remainder:
1802 return None
1803 if y.sign == 1:
1804 exponent = -exponent
1805 # if other is a nonnegative integer, use ideal exponent
1806 if other._isinteger() and other._sign == 0:
1807 ideal_exponent = self._exp*int(other)
1808 zeros = min(exponent-ideal_exponent, p-1)
1809 else:
1810 zeros = 0
1811 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1813 # case where y is negative: xc must be either a power
1814 # of 2 or a power of 5.
1815 if y.sign == 1:
1816 last_digit = xc % 10
1817 if last_digit in (2,4,6,8):
1818 # quick test for power of 2
1819 if xc & -xc != xc:
1820 return None
1821 # now xc is a power of 2; e is its exponent
1822 e = _nbits(xc)-1
1823 # find e*y and xe*y; both must be integers
1824 if ye >= 0:
1825 y_as_int = yc*10**ye
1826 e = e*y_as_int
1827 xe = xe*y_as_int
1828 else:
1829 ten_pow = 10**-ye
1830 e, remainder = divmod(e*yc, ten_pow)
1831 if remainder:
1832 return None
1833 xe, remainder = divmod(xe*yc, ten_pow)
1834 if remainder:
1835 return None
1837 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1838 return None
1839 xc = 5**e
1841 elif last_digit == 5:
1842 # e >= log_5(xc) if xc is a power of 5; we have
1843 # equality all the way up to xc=5**2658
1844 e = _nbits(xc)*28//65
1845 xc, remainder = divmod(5**e, xc)
1846 if remainder:
1847 return None
1848 while xc % 5 == 0:
1849 xc //= 5
1850 e -= 1
1851 if ye >= 0:
1852 y_as_integer = yc*10**ye
1853 e = e*y_as_integer
1854 xe = xe*y_as_integer
1855 else:
1856 ten_pow = 10**-ye
1857 e, remainder = divmod(e*yc, ten_pow)
1858 if remainder:
1859 return None
1860 xe, remainder = divmod(xe*yc, ten_pow)
1861 if remainder:
1862 return None
1863 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1864 return None
1865 xc = 2**e
1866 else:
1867 return None
1869 if xc >= 10**p:
1870 return None
1871 xe = -e-xe
1872 return _dec_from_triple(0, str(xc), xe)
1874 # now y is positive; find m and n such that y = m/n
1875 if ye >= 0:
1876 m, n = yc*10**ye, 1
1877 else:
1878 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1879 return None
1880 xc_bits = _nbits(xc)
1881 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1882 return None
1883 m, n = yc, 10**(-ye)
1884 while m % 2 == n % 2 == 0:
1885 m //= 2
1886 n //= 2
1887 while m % 5 == n % 5 == 0:
1888 m //= 5
1889 n //= 5
1891 # compute nth root of xc*10**xe
1892 if n > 1:
1893 # if 1 < xc < 2**n then xc isn't an nth power
1894 if xc != 1 and xc_bits <= n:
1895 return None
1897 xe, rem = divmod(xe, n)
1898 if rem != 0:
1899 return None
1901 # compute nth root of xc using Newton's method
1902 a = 1L << -(-_nbits(xc)//n) # initial estimate
1903 while True:
1904 q, r = divmod(xc, a**(n-1))
1905 if a <= q:
1906 break
1907 else:
1908 a = (a*(n-1) + q)//n
1909 if not (a == q and r == 0):
1910 return None
1911 xc = a
1913 # now xc*10**xe is the nth root of the original xc*10**xe
1914 # compute mth power of xc*10**xe
1916 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
1917 # 10**p and the result is not representable.
1918 if xc > 1 and m > p*100//_log10_lb(xc):
1919 return None
1920 xc = xc**m
1921 xe *= m
1922 if xc > 10**p:
1923 return None
1925 # by this point the result *is* exactly representable
1926 # adjust the exponent to get as close as possible to the ideal
1927 # exponent, if necessary
1928 str_xc = str(xc)
1929 if other._isinteger() and other._sign == 0:
1930 ideal_exponent = self._exp*int(other)
1931 zeros = min(xe-ideal_exponent, p-len(str_xc))
1932 else:
1933 zeros = 0
1934 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
1936 def __pow__(self, other, modulo=None, context=None):
1937 """Return self ** other [ % modulo].
1939 With two arguments, compute self**other.
1941 With three arguments, compute (self**other) % modulo. For the
1942 three argument form, the following restrictions on the
1943 arguments hold:
1945 - all three arguments must be integral
1946 - other must be nonnegative
1947 - either self or other (or both) must be nonzero
1948 - modulo must be nonzero and must have at most p digits,
1949 where p is the context precision.
1951 If any of these restrictions is violated the InvalidOperation
1952 flag is raised.
1954 The result of pow(self, other, modulo) is identical to the
1955 result that would be obtained by computing (self**other) %
1956 modulo with unbounded precision, but is computed more
1957 efficiently. It is always exact.
1960 if modulo is not None:
1961 return self._power_modulo(other, modulo, context)
1963 other = _convert_other(other)
1964 if other is NotImplemented:
1965 return other
1967 if context is None:
1968 context = getcontext()
1970 # either argument is a NaN => result is NaN
1971 ans = self._check_nans(other, context)
1972 if ans:
1973 return ans
1975 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
1976 if not other:
1977 if not self:
1978 return context._raise_error(InvalidOperation, '0 ** 0')
1979 else:
1980 return Dec_p1
1982 # result has sign 1 iff self._sign is 1 and other is an odd integer
1983 result_sign = 0
1984 if self._sign == 1:
1985 if other._isinteger():
1986 if not other._iseven():
1987 result_sign = 1
1988 else:
1989 # -ve**noninteger = NaN
1990 # (-0)**noninteger = 0**noninteger
1991 if self:
1992 return context._raise_error(InvalidOperation,
1993 'x ** y with x negative and y not an integer')
1994 # negate self, without doing any unwanted rounding
1995 self = self.copy_negate()
1997 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
1998 if not self:
1999 if other._sign == 0:
2000 return _dec_from_triple(result_sign, '0', 0)
2001 else:
2002 return Infsign[result_sign]
2004 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2005 if self._isinfinity():
2006 if other._sign == 0:
2007 return Infsign[result_sign]
2008 else:
2009 return _dec_from_triple(result_sign, '0', 0)
2011 # 1**other = 1, but the choice of exponent and the flags
2012 # depend on the exponent of self, and on whether other is a
2013 # positive integer, a negative integer, or neither
2014 if self == Dec_p1:
2015 if other._isinteger():
2016 # exp = max(self._exp*max(int(other), 0),
2017 # 1-context.prec) but evaluating int(other) directly
2018 # is dangerous until we know other is small (other
2019 # could be 1e999999999)
2020 if other._sign == 1:
2021 multiplier = 0
2022 elif other > context.prec:
2023 multiplier = context.prec
2024 else:
2025 multiplier = int(other)
2027 exp = self._exp * multiplier
2028 if exp < 1-context.prec:
2029 exp = 1-context.prec
2030 context._raise_error(Rounded)
2031 else:
2032 context._raise_error(Inexact)
2033 context._raise_error(Rounded)
2034 exp = 1-context.prec
2036 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2038 # compute adjusted exponent of self
2039 self_adj = self.adjusted()
2041 # self ** infinity is infinity if self > 1, 0 if self < 1
2042 # self ** -infinity is infinity if self < 1, 0 if self > 1
2043 if other._isinfinity():
2044 if (other._sign == 0) == (self_adj < 0):
2045 return _dec_from_triple(result_sign, '0', 0)
2046 else:
2047 return Infsign[result_sign]
2049 # from here on, the result always goes through the call
2050 # to _fix at the end of this function.
2051 ans = None
2053 # crude test to catch cases of extreme overflow/underflow. If
2054 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2055 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2056 # self**other >= 10**(Emax+1), so overflow occurs. The test
2057 # for underflow is similar.
2058 bound = self._log10_exp_bound() + other.adjusted()
2059 if (self_adj >= 0) == (other._sign == 0):
2060 # self > 1 and other +ve, or self < 1 and other -ve
2061 # possibility of overflow
2062 if bound >= len(str(context.Emax)):
2063 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2064 else:
2065 # self > 1 and other -ve, or self < 1 and other +ve
2066 # possibility of underflow to 0
2067 Etiny = context.Etiny()
2068 if bound >= len(str(-Etiny)):
2069 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2071 # try for an exact result with precision +1
2072 if ans is None:
2073 ans = self._power_exact(other, context.prec + 1)
2074 if ans is not None and result_sign == 1:
2075 ans = _dec_from_triple(1, ans._int, ans._exp)
2077 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2078 if ans is None:
2079 p = context.prec
2080 x = _WorkRep(self)
2081 xc, xe = x.int, x.exp
2082 y = _WorkRep(other)
2083 yc, ye = y.int, y.exp
2084 if y.sign == 1:
2085 yc = -yc
2087 # compute correctly rounded result: start with precision +3,
2088 # then increase precision until result is unambiguously roundable
2089 extra = 3
2090 while True:
2091 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2092 if coeff % (5*10**(len(str(coeff))-p-1)):
2093 break
2094 extra += 3
2096 ans = _dec_from_triple(result_sign, str(coeff), exp)
2098 # the specification says that for non-integer other we need to
2099 # raise Inexact, even when the result is actually exact. In
2100 # the same way, we need to raise Underflow here if the result
2101 # is subnormal. (The call to _fix will take care of raising
2102 # Rounded and Subnormal, as usual.)
2103 if not other._isinteger():
2104 context._raise_error(Inexact)
2105 # pad with zeros up to length context.prec+1 if necessary
2106 if len(ans._int) <= context.prec:
2107 expdiff = context.prec+1 - len(ans._int)
2108 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2109 ans._exp-expdiff)
2110 if ans.adjusted() < context.Emin:
2111 context._raise_error(Underflow)
2113 # unlike exp, ln and log10, the power function respects the
2114 # rounding mode; no need to use ROUND_HALF_EVEN here
2115 ans = ans._fix(context)
2116 return ans
2118 def __rpow__(self, other, context=None):
2119 """Swaps self/other and returns __pow__."""
2120 other = _convert_other(other)
2121 if other is NotImplemented:
2122 return other
2123 return other.__pow__(self, context=context)
2125 def normalize(self, context=None):
2126 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2128 if context is None:
2129 context = getcontext()
2131 if self._is_special:
2132 ans = self._check_nans(context=context)
2133 if ans:
2134 return ans
2136 dup = self._fix(context)
2137 if dup._isinfinity():
2138 return dup
2140 if not dup:
2141 return _dec_from_triple(dup._sign, '0', 0)
2142 exp_max = [context.Emax, context.Etop()][context._clamp]
2143 end = len(dup._int)
2144 exp = dup._exp
2145 while dup._int[end-1] == '0' and exp < exp_max:
2146 exp += 1
2147 end -= 1
2148 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2150 def quantize(self, exp, rounding=None, context=None, watchexp=True):
2151 """Quantize self so its exponent is the same as that of exp.
2153 Similar to self._rescale(exp._exp) but with error checking.
2155 exp = _convert_other(exp, raiseit=True)
2157 if context is None:
2158 context = getcontext()
2159 if rounding is None:
2160 rounding = context.rounding
2162 if self._is_special or exp._is_special:
2163 ans = self._check_nans(exp, context)
2164 if ans:
2165 return ans
2167 if exp._isinfinity() or self._isinfinity():
2168 if exp._isinfinity() and self._isinfinity():
2169 return Decimal(self) # if both are inf, it is OK
2170 return context._raise_error(InvalidOperation,
2171 'quantize with one INF')
2173 # if we're not watching exponents, do a simple rescale
2174 if not watchexp:
2175 ans = self._rescale(exp._exp, rounding)
2176 # raise Inexact and Rounded where appropriate
2177 if ans._exp > self._exp:
2178 context._raise_error(Rounded)
2179 if ans != self:
2180 context._raise_error(Inexact)
2181 return ans
2183 # exp._exp should be between Etiny and Emax
2184 if not (context.Etiny() <= exp._exp <= context.Emax):
2185 return context._raise_error(InvalidOperation,
2186 'target exponent out of bounds in quantize')
2188 if not self:
2189 ans = _dec_from_triple(self._sign, '0', exp._exp)
2190 return ans._fix(context)
2192 self_adjusted = self.adjusted()
2193 if self_adjusted > context.Emax:
2194 return context._raise_error(InvalidOperation,
2195 'exponent of quantize result too large for current context')
2196 if self_adjusted - exp._exp + 1 > context.prec:
2197 return context._raise_error(InvalidOperation,
2198 'quantize result has too many digits for current context')
2200 ans = self._rescale(exp._exp, rounding)
2201 if ans.adjusted() > context.Emax:
2202 return context._raise_error(InvalidOperation,
2203 'exponent of quantize result too large for current context')
2204 if len(ans._int) > context.prec:
2205 return context._raise_error(InvalidOperation,
2206 'quantize result has too many digits for current context')
2208 # raise appropriate flags
2209 if ans._exp > self._exp:
2210 context._raise_error(Rounded)
2211 if ans != self:
2212 context._raise_error(Inexact)
2213 if ans and ans.adjusted() < context.Emin:
2214 context._raise_error(Subnormal)
2216 # call to fix takes care of any necessary folddown
2217 ans = ans._fix(context)
2218 return ans
2220 def same_quantum(self, other):
2221 """Return True if self and other have the same exponent; otherwise
2222 return False.
2224 If either operand is a special value, the following rules are used:
2225 * return True if both operands are infinities
2226 * return True if both operands are NaNs
2227 * otherwise, return False.
2229 other = _convert_other(other, raiseit=True)
2230 if self._is_special or other._is_special:
2231 return (self.is_nan() and other.is_nan() or
2232 self.is_infinite() and other.is_infinite())
2233 return self._exp == other._exp
2235 def _rescale(self, exp, rounding):
2236 """Rescale self so that the exponent is exp, either by padding with zeros
2237 or by truncating digits, using the given rounding mode.
2239 Specials are returned without change. This operation is
2240 quiet: it raises no flags, and uses no information from the
2241 context.
2243 exp = exp to scale to (an integer)
2244 rounding = rounding mode
2246 if self._is_special:
2247 return Decimal(self)
2248 if not self:
2249 return _dec_from_triple(self._sign, '0', exp)
2251 if self._exp >= exp:
2252 # pad answer with zeros if necessary
2253 return _dec_from_triple(self._sign,
2254 self._int + '0'*(self._exp - exp), exp)
2256 # too many digits; round and lose data. If self.adjusted() <
2257 # exp-1, replace self by 10**(exp-1) before rounding
2258 digits = len(self._int) + self._exp - exp
2259 if digits < 0:
2260 self = _dec_from_triple(self._sign, '1', exp-1)
2261 digits = 0
2262 this_function = getattr(self, self._pick_rounding_function[rounding])
2263 changed = this_function(digits)
2264 coeff = self._int[:digits] or '0'
2265 if changed == 1:
2266 coeff = str(int(coeff)+1)
2267 return _dec_from_triple(self._sign, coeff, exp)
2269 def to_integral_exact(self, rounding=None, context=None):
2270 """Rounds to a nearby integer.
2272 If no rounding mode is specified, take the rounding mode from
2273 the context. This method raises the Rounded and Inexact flags
2274 when appropriate.
2276 See also: to_integral_value, which does exactly the same as
2277 this method except that it doesn't raise Inexact or Rounded.
2279 if self._is_special:
2280 ans = self._check_nans(context=context)
2281 if ans:
2282 return ans
2283 return Decimal(self)
2284 if self._exp >= 0:
2285 return Decimal(self)
2286 if not self:
2287 return _dec_from_triple(self._sign, '0', 0)
2288 if context is None:
2289 context = getcontext()
2290 if rounding is None:
2291 rounding = context.rounding
2292 context._raise_error(Rounded)
2293 ans = self._rescale(0, rounding)
2294 if ans != self:
2295 context._raise_error(Inexact)
2296 return ans
2298 def to_integral_value(self, rounding=None, context=None):
2299 """Rounds to the nearest integer, without raising inexact, rounded."""
2300 if context is None:
2301 context = getcontext()
2302 if rounding is None:
2303 rounding = context.rounding
2304 if self._is_special:
2305 ans = self._check_nans(context=context)
2306 if ans:
2307 return ans
2308 return Decimal(self)
2309 if self._exp >= 0:
2310 return Decimal(self)
2311 else:
2312 return self._rescale(0, rounding)
2314 # the method name changed, but we provide also the old one, for compatibility
2315 to_integral = to_integral_value
2317 def sqrt(self, context=None):
2318 """Return the square root of self."""
2319 if self._is_special:
2320 ans = self._check_nans(context=context)
2321 if ans:
2322 return ans
2324 if self._isinfinity() and self._sign == 0:
2325 return Decimal(self)
2327 if not self:
2328 # exponent = self._exp // 2. sqrt(-0) = -0
2329 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2330 return ans._fix(context)
2332 if context is None:
2333 context = getcontext()
2335 if self._sign == 1:
2336 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2338 # At this point self represents a positive number. Let p be
2339 # the desired precision and express self in the form c*100**e
2340 # with c a positive real number and e an integer, c and e
2341 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2342 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2343 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2344 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2345 # the closest integer to sqrt(c) with the even integer chosen
2346 # in the case of a tie.
2348 # To ensure correct rounding in all cases, we use the
2349 # following trick: we compute the square root to an extra
2350 # place (precision p+1 instead of precision p), rounding down.
2351 # Then, if the result is inexact and its last digit is 0 or 5,
2352 # we increase the last digit to 1 or 6 respectively; if it's
2353 # exact we leave the last digit alone. Now the final round to
2354 # p places (or fewer in the case of underflow) will round
2355 # correctly and raise the appropriate flags.
2357 # use an extra digit of precision
2358 prec = context.prec+1
2360 # write argument in the form c*100**e where e = self._exp//2
2361 # is the 'ideal' exponent, to be used if the square root is
2362 # exactly representable. l is the number of 'digits' of c in
2363 # base 100, so that 100**(l-1) <= c < 100**l.
2364 op = _WorkRep(self)
2365 e = op.exp >> 1
2366 if op.exp & 1:
2367 c = op.int * 10
2368 l = (len(self._int) >> 1) + 1
2369 else:
2370 c = op.int
2371 l = len(self._int)+1 >> 1
2373 # rescale so that c has exactly prec base 100 'digits'
2374 shift = prec-l
2375 if shift >= 0:
2376 c *= 100**shift
2377 exact = True
2378 else:
2379 c, remainder = divmod(c, 100**-shift)
2380 exact = not remainder
2381 e -= shift
2383 # find n = floor(sqrt(c)) using Newton's method
2384 n = 10**prec
2385 while True:
2386 q = c//n
2387 if n <= q:
2388 break
2389 else:
2390 n = n + q >> 1
2391 exact = exact and n*n == c
2393 if exact:
2394 # result is exact; rescale to use ideal exponent e
2395 if shift >= 0:
2396 # assert n % 10**shift == 0
2397 n //= 10**shift
2398 else:
2399 n *= 10**-shift
2400 e += shift
2401 else:
2402 # result is not exact; fix last digit as described above
2403 if n % 5 == 0:
2404 n += 1
2406 ans = _dec_from_triple(0, str(n), e)
2408 # round, and fit to current context
2409 context = context._shallow_copy()
2410 rounding = context._set_rounding(ROUND_HALF_EVEN)
2411 ans = ans._fix(context)
2412 context.rounding = rounding
2414 return ans
2416 def max(self, other, context=None):
2417 """Returns the larger value.
2419 Like max(self, other) except if one is not a number, returns
2420 NaN (and signals if one is sNaN). Also rounds.
2422 other = _convert_other(other, raiseit=True)
2424 if context is None:
2425 context = getcontext()
2427 if self._is_special or other._is_special:
2428 # If one operand is a quiet NaN and the other is number, then the
2429 # number is always returned
2430 sn = self._isnan()
2431 on = other._isnan()
2432 if sn or on:
2433 if on == 1 and sn != 2:
2434 return self._fix_nan(context)
2435 if sn == 1 and on != 2:
2436 return other._fix_nan(context)
2437 return self._check_nans(other, context)
2439 c = self.__cmp__(other)
2440 if c == 0:
2441 # If both operands are finite and equal in numerical value
2442 # then an ordering is applied:
2444 # If the signs differ then max returns the operand with the
2445 # positive sign and min returns the operand with the negative sign
2447 # If the signs are the same then the exponent is used to select
2448 # the result. This is exactly the ordering used in compare_total.
2449 c = self.compare_total(other)
2451 if c == -1:
2452 ans = other
2453 else:
2454 ans = self
2456 return ans._fix(context)
2458 def min(self, other, context=None):
2459 """Returns the smaller value.
2461 Like min(self, other) except if one is not a number, returns
2462 NaN (and signals if one is sNaN). Also rounds.
2464 other = _convert_other(other, raiseit=True)
2466 if context is None:
2467 context = getcontext()
2469 if self._is_special or other._is_special:
2470 # If one operand is a quiet NaN and the other is number, then the
2471 # number is always returned
2472 sn = self._isnan()
2473 on = other._isnan()
2474 if sn or on:
2475 if on == 1 and sn != 2:
2476 return self._fix_nan(context)
2477 if sn == 1 and on != 2:
2478 return other._fix_nan(context)
2479 return self._check_nans(other, context)
2481 c = self.__cmp__(other)
2482 if c == 0:
2483 c = self.compare_total(other)
2485 if c == -1:
2486 ans = self
2487 else:
2488 ans = other
2490 return ans._fix(context)
2492 def _isinteger(self):
2493 """Returns whether self is an integer"""
2494 if self._is_special:
2495 return False
2496 if self._exp >= 0:
2497 return True
2498 rest = self._int[self._exp:]
2499 return rest == '0'*len(rest)
2501 def _iseven(self):
2502 """Returns True if self is even. Assumes self is an integer."""
2503 if not self or self._exp > 0:
2504 return True
2505 return self._int[-1+self._exp] in '02468'
2507 def adjusted(self):
2508 """Return the adjusted exponent of self"""
2509 try:
2510 return self._exp + len(self._int) - 1
2511 # If NaN or Infinity, self._exp is string
2512 except TypeError:
2513 return 0
2515 def canonical(self, context=None):
2516 """Returns the same Decimal object.
2518 As we do not have different encodings for the same number, the
2519 received object already is in its canonical form.
2521 return self
2523 def compare_signal(self, other, context=None):
2524 """Compares self to the other operand numerically.
2526 It's pretty much like compare(), but all NaNs signal, with signaling
2527 NaNs taking precedence over quiet NaNs.
2529 if context is None:
2530 context = getcontext()
2532 self_is_nan = self._isnan()
2533 other_is_nan = other._isnan()
2534 if self_is_nan == 2:
2535 return context._raise_error(InvalidOperation, 'sNaN',
2536 self)
2537 if other_is_nan == 2:
2538 return context._raise_error(InvalidOperation, 'sNaN',
2539 other)
2540 if self_is_nan:
2541 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2542 self)
2543 if other_is_nan:
2544 return context._raise_error(InvalidOperation, 'NaN in compare_signal',
2545 other)
2546 return self.compare(other, context=context)
2548 def compare_total(self, other):
2549 """Compares self to other using the abstract representations.
2551 This is not like the standard compare, which use their numerical
2552 value. Note that a total ordering is defined for all possible abstract
2553 representations.
2555 # if one is negative and the other is positive, it's easy
2556 if self._sign and not other._sign:
2557 return Dec_n1
2558 if not self._sign and other._sign:
2559 return Dec_p1
2560 sign = self._sign
2562 # let's handle both NaN types
2563 self_nan = self._isnan()
2564 other_nan = other._isnan()
2565 if self_nan or other_nan:
2566 if self_nan == other_nan:
2567 if self._int < other._int:
2568 if sign:
2569 return Dec_p1
2570 else:
2571 return Dec_n1
2572 if self._int > other._int:
2573 if sign:
2574 return Dec_n1
2575 else:
2576 return Dec_p1
2577 return Dec_0
2579 if sign:
2580 if self_nan == 1:
2581 return Dec_n1
2582 if other_nan == 1:
2583 return Dec_p1
2584 if self_nan == 2:
2585 return Dec_n1
2586 if other_nan == 2:
2587 return Dec_p1
2588 else:
2589 if self_nan == 1:
2590 return Dec_p1
2591 if other_nan == 1:
2592 return Dec_n1
2593 if self_nan == 2:
2594 return Dec_p1
2595 if other_nan == 2:
2596 return Dec_n1
2598 if self < other:
2599 return Dec_n1
2600 if self > other:
2601 return Dec_p1
2603 if self._exp < other._exp:
2604 if sign:
2605 return Dec_p1
2606 else:
2607 return Dec_n1
2608 if self._exp > other._exp:
2609 if sign:
2610 return Dec_n1
2611 else:
2612 return Dec_p1
2613 return Dec_0
2616 def compare_total_mag(self, other):
2617 """Compares self to other using abstract repr., ignoring sign.
2619 Like compare_total, but with operand's sign ignored and assumed to be 0.
2621 s = self.copy_abs()
2622 o = other.copy_abs()
2623 return s.compare_total(o)
2625 def copy_abs(self):
2626 """Returns a copy with the sign set to 0. """
2627 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2629 def copy_negate(self):
2630 """Returns a copy with the sign inverted."""
2631 if self._sign:
2632 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2633 else:
2634 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2636 def copy_sign(self, other):
2637 """Returns self with the sign of other."""
2638 return _dec_from_triple(other._sign, self._int,
2639 self._exp, self._is_special)
2641 def exp(self, context=None):
2642 """Returns e ** self."""
2644 if context is None:
2645 context = getcontext()
2647 # exp(NaN) = NaN
2648 ans = self._check_nans(context=context)
2649 if ans:
2650 return ans
2652 # exp(-Infinity) = 0
2653 if self._isinfinity() == -1:
2654 return Dec_0
2656 # exp(0) = 1
2657 if not self:
2658 return Dec_p1
2660 # exp(Infinity) = Infinity
2661 if self._isinfinity() == 1:
2662 return Decimal(self)
2664 # the result is now guaranteed to be inexact (the true
2665 # mathematical result is transcendental). There's no need to
2666 # raise Rounded and Inexact here---they'll always be raised as
2667 # a result of the call to _fix.
2668 p = context.prec
2669 adj = self.adjusted()
2671 # we only need to do any computation for quite a small range
2672 # of adjusted exponents---for example, -29 <= adj <= 10 for
2673 # the default context. For smaller exponent the result is
2674 # indistinguishable from 1 at the given precision, while for
2675 # larger exponent the result either overflows or underflows.
2676 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2677 # overflow
2678 ans = _dec_from_triple(0, '1', context.Emax+1)
2679 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2680 # underflow to 0
2681 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2682 elif self._sign == 0 and adj < -p:
2683 # p+1 digits; final round will raise correct flags
2684 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2685 elif self._sign == 1 and adj < -p-1:
2686 # p+1 digits; final round will raise correct flags
2687 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2688 # general case
2689 else:
2690 op = _WorkRep(self)
2691 c, e = op.int, op.exp
2692 if op.sign == 1:
2693 c = -c
2695 # compute correctly rounded result: increase precision by
2696 # 3 digits at a time until we get an unambiguously
2697 # roundable result
2698 extra = 3
2699 while True:
2700 coeff, exp = _dexp(c, e, p+extra)
2701 if coeff % (5*10**(len(str(coeff))-p-1)):
2702 break
2703 extra += 3
2705 ans = _dec_from_triple(0, str(coeff), exp)
2707 # at this stage, ans should round correctly with *any*
2708 # rounding mode, not just with ROUND_HALF_EVEN
2709 context = context._shallow_copy()
2710 rounding = context._set_rounding(ROUND_HALF_EVEN)
2711 ans = ans._fix(context)
2712 context.rounding = rounding
2714 return ans
2716 def is_canonical(self):
2717 """Return True if self is canonical; otherwise return False.
2719 Currently, the encoding of a Decimal instance is always
2720 canonical, so this method returns True for any Decimal.
2722 return True
2724 def is_finite(self):
2725 """Return True if self is finite; otherwise return False.
2727 A Decimal instance is considered finite if it is neither
2728 infinite nor a NaN.
2730 return not self._is_special
2732 def is_infinite(self):
2733 """Return True if self is infinite; otherwise return False."""
2734 return self._exp == 'F'
2736 def is_nan(self):
2737 """Return True if self is a qNaN or sNaN; otherwise return False."""
2738 return self._exp in ('n', 'N')
2740 def is_normal(self, context=None):
2741 """Return True if self is a normal number; otherwise return False."""
2742 if self._is_special or not self:
2743 return False
2744 if context is None:
2745 context = getcontext()
2746 return context.Emin <= self.adjusted() <= context.Emax
2748 def is_qnan(self):
2749 """Return True if self is a quiet NaN; otherwise return False."""
2750 return self._exp == 'n'
2752 def is_signed(self):
2753 """Return True if self is negative; otherwise return False."""
2754 return self._sign == 1
2756 def is_snan(self):
2757 """Return True if self is a signaling NaN; otherwise return False."""
2758 return self._exp == 'N'
2760 def is_subnormal(self, context=None):
2761 """Return True if self is subnormal; otherwise return False."""
2762 if self._is_special or not self:
2763 return False
2764 if context is None:
2765 context = getcontext()
2766 return self.adjusted() < context.Emin
2768 def is_zero(self):
2769 """Return True if self is a zero; otherwise return False."""
2770 return not self._is_special and self._int == '0'
2772 def _ln_exp_bound(self):
2773 """Compute a lower bound for the adjusted exponent of self.ln().
2774 In other words, compute r such that self.ln() >= 10**r. Assumes
2775 that self is finite and positive and that self != 1.
2778 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2779 adj = self._exp + len(self._int) - 1
2780 if adj >= 1:
2781 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2782 return len(str(adj*23//10)) - 1
2783 if adj <= -2:
2784 # argument <= 0.1
2785 return len(str((-1-adj)*23//10)) - 1
2786 op = _WorkRep(self)
2787 c, e = op.int, op.exp
2788 if adj == 0:
2789 # 1 < self < 10
2790 num = str(c-10**-e)
2791 den = str(c)
2792 return len(num) - len(den) - (num < den)
2793 # adj == -1, 0.1 <= self < 1
2794 return e + len(str(10**-e - c)) - 1
2797 def ln(self, context=None):
2798 """Returns the natural (base e) logarithm of self."""
2800 if context is None:
2801 context = getcontext()
2803 # ln(NaN) = NaN
2804 ans = self._check_nans(context=context)
2805 if ans:
2806 return ans
2808 # ln(0.0) == -Infinity
2809 if not self:
2810 return negInf
2812 # ln(Infinity) = Infinity
2813 if self._isinfinity() == 1:
2814 return Inf
2816 # ln(1.0) == 0.0
2817 if self == Dec_p1:
2818 return Dec_0
2820 # ln(negative) raises InvalidOperation
2821 if self._sign == 1:
2822 return context._raise_error(InvalidOperation,
2823 'ln of a negative value')
2825 # result is irrational, so necessarily inexact
2826 op = _WorkRep(self)
2827 c, e = op.int, op.exp
2828 p = context.prec
2830 # correctly rounded result: repeatedly increase precision by 3
2831 # until we get an unambiguously roundable result
2832 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2833 while True:
2834 coeff = _dlog(c, e, places)
2835 # assert len(str(abs(coeff)))-p >= 1
2836 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2837 break
2838 places += 3
2839 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2841 context = context._shallow_copy()
2842 rounding = context._set_rounding(ROUND_HALF_EVEN)
2843 ans = ans._fix(context)
2844 context.rounding = rounding
2845 return ans
2847 def _log10_exp_bound(self):
2848 """Compute a lower bound for the adjusted exponent of self.log10().
2849 In other words, find r such that self.log10() >= 10**r.
2850 Assumes that self is finite and positive and that self != 1.
2853 # For x >= 10 or x < 0.1 we only need a bound on the integer
2854 # part of log10(self), and this comes directly from the
2855 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2856 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2857 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2859 adj = self._exp + len(self._int) - 1
2860 if adj >= 1:
2861 # self >= 10
2862 return len(str(adj))-1
2863 if adj <= -2:
2864 # self < 0.1
2865 return len(str(-1-adj))-1
2866 op = _WorkRep(self)
2867 c, e = op.int, op.exp
2868 if adj == 0:
2869 # 1 < self < 10
2870 num = str(c-10**-e)
2871 den = str(231*c)
2872 return len(num) - len(den) - (num < den) + 2
2873 # adj == -1, 0.1 <= self < 1
2874 num = str(10**-e-c)
2875 return len(num) + e - (num < "231") - 1
2877 def log10(self, context=None):
2878 """Returns the base 10 logarithm of self."""
2880 if context is None:
2881 context = getcontext()
2883 # log10(NaN) = NaN
2884 ans = self._check_nans(context=context)
2885 if ans:
2886 return ans
2888 # log10(0.0) == -Infinity
2889 if not self:
2890 return negInf
2892 # log10(Infinity) = Infinity
2893 if self._isinfinity() == 1:
2894 return Inf
2896 # log10(negative or -Infinity) raises InvalidOperation
2897 if self._sign == 1:
2898 return context._raise_error(InvalidOperation,
2899 'log10 of a negative value')
2901 # log10(10**n) = n
2902 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
2903 # answer may need rounding
2904 ans = Decimal(self._exp + len(self._int) - 1)
2905 else:
2906 # result is irrational, so necessarily inexact
2907 op = _WorkRep(self)
2908 c, e = op.int, op.exp
2909 p = context.prec
2911 # correctly rounded result: repeatedly increase precision
2912 # until result is unambiguously roundable
2913 places = p-self._log10_exp_bound()+2
2914 while True:
2915 coeff = _dlog10(c, e, places)
2916 # assert len(str(abs(coeff)))-p >= 1
2917 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2918 break
2919 places += 3
2920 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2922 context = context._shallow_copy()
2923 rounding = context._set_rounding(ROUND_HALF_EVEN)
2924 ans = ans._fix(context)
2925 context.rounding = rounding
2926 return ans
2928 def logb(self, context=None):
2929 """ Returns the exponent of the magnitude of self's MSD.
2931 The result is the integer which is the exponent of the magnitude
2932 of the most significant digit of self (as though it were truncated
2933 to a single digit while maintaining the value of that digit and
2934 without limiting the resulting exponent).
2936 # logb(NaN) = NaN
2937 ans = self._check_nans(context=context)
2938 if ans:
2939 return ans
2941 if context is None:
2942 context = getcontext()
2944 # logb(+/-Inf) = +Inf
2945 if self._isinfinity():
2946 return Inf
2948 # logb(0) = -Inf, DivisionByZero
2949 if not self:
2950 return context._raise_error(DivisionByZero, 'logb(0)', 1)
2952 # otherwise, simply return the adjusted exponent of self, as a
2953 # Decimal. Note that no attempt is made to fit the result
2954 # into the current context.
2955 return Decimal(self.adjusted())
2957 def _islogical(self):
2958 """Return True if self is a logical operand.
2960 For being logical, it must be a finite numbers with a sign of 0,
2961 an exponent of 0, and a coefficient whose digits must all be
2962 either 0 or 1.
2964 if self._sign != 0 or self._exp != 0:
2965 return False
2966 for dig in self._int:
2967 if dig not in '01':
2968 return False
2969 return True
2971 def _fill_logical(self, context, opa, opb):
2972 dif = context.prec - len(opa)
2973 if dif > 0:
2974 opa = '0'*dif + opa
2975 elif dif < 0:
2976 opa = opa[-context.prec:]
2977 dif = context.prec - len(opb)
2978 if dif > 0:
2979 opb = '0'*dif + opb
2980 elif dif < 0:
2981 opb = opb[-context.prec:]
2982 return opa, opb
2984 def logical_and(self, other, context=None):
2985 """Applies an 'and' operation between self and other's digits."""
2986 if context is None:
2987 context = getcontext()
2988 if not self._islogical() or not other._islogical():
2989 return context._raise_error(InvalidOperation)
2991 # fill to context.prec
2992 (opa, opb) = self._fill_logical(context, self._int, other._int)
2994 # make the operation, and clean starting zeroes
2995 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
2996 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
2998 def logical_invert(self, context=None):
2999 """Invert all its digits."""
3000 if context is None:
3001 context = getcontext()
3002 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3003 context)
3005 def logical_or(self, other, context=None):
3006 """Applies an 'or' operation between self and other's digits."""
3007 if context is None:
3008 context = getcontext()
3009 if not self._islogical() or not other._islogical():
3010 return context._raise_error(InvalidOperation)
3012 # fill to context.prec
3013 (opa, opb) = self._fill_logical(context, self._int, other._int)
3015 # make the operation, and clean starting zeroes
3016 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3017 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3019 def logical_xor(self, other, context=None):
3020 """Applies an 'xor' operation between self and other's digits."""
3021 if context is None:
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 max_mag(self, other, context=None):
3034 """Compares the values numerically with their sign ignored."""
3035 other = _convert_other(other, raiseit=True)
3037 if context is None:
3038 context = getcontext()
3040 if self._is_special or other._is_special:
3041 # If one operand is a quiet NaN and the other is number, then the
3042 # number is always returned
3043 sn = self._isnan()
3044 on = other._isnan()
3045 if sn or on:
3046 if on == 1 and sn != 2:
3047 return self._fix_nan(context)
3048 if sn == 1 and on != 2:
3049 return other._fix_nan(context)
3050 return self._check_nans(other, context)
3052 c = self.copy_abs().__cmp__(other.copy_abs())
3053 if c == 0:
3054 c = self.compare_total(other)
3056 if c == -1:
3057 ans = other
3058 else:
3059 ans = self
3061 return ans._fix(context)
3063 def min_mag(self, other, context=None):
3064 """Compares the values numerically with their sign ignored."""
3065 other = _convert_other(other, raiseit=True)
3067 if context is None:
3068 context = getcontext()
3070 if self._is_special or other._is_special:
3071 # If one operand is a quiet NaN and the other is number, then the
3072 # number is always returned
3073 sn = self._isnan()
3074 on = other._isnan()
3075 if sn or on:
3076 if on == 1 and sn != 2:
3077 return self._fix_nan(context)
3078 if sn == 1 and on != 2:
3079 return other._fix_nan(context)
3080 return self._check_nans(other, context)
3082 c = self.copy_abs().__cmp__(other.copy_abs())
3083 if c == 0:
3084 c = self.compare_total(other)
3086 if c == -1:
3087 ans = self
3088 else:
3089 ans = other
3091 return ans._fix(context)
3093 def next_minus(self, context=None):
3094 """Returns the largest representable number smaller than itself."""
3095 if context is None:
3096 context = getcontext()
3098 ans = self._check_nans(context=context)
3099 if ans:
3100 return ans
3102 if self._isinfinity() == -1:
3103 return negInf
3104 if self._isinfinity() == 1:
3105 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3107 context = context.copy()
3108 context._set_rounding(ROUND_FLOOR)
3109 context._ignore_all_flags()
3110 new_self = self._fix(context)
3111 if new_self != self:
3112 return new_self
3113 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3114 context)
3116 def next_plus(self, context=None):
3117 """Returns the smallest representable number larger than itself."""
3118 if context is None:
3119 context = getcontext()
3121 ans = self._check_nans(context=context)
3122 if ans:
3123 return ans
3125 if self._isinfinity() == 1:
3126 return Inf
3127 if self._isinfinity() == -1:
3128 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3130 context = context.copy()
3131 context._set_rounding(ROUND_CEILING)
3132 context._ignore_all_flags()
3133 new_self = self._fix(context)
3134 if new_self != self:
3135 return new_self
3136 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3137 context)
3139 def next_toward(self, other, context=None):
3140 """Returns the number closest to self, in the direction towards other.
3142 The result is the closest representable number to self
3143 (excluding self) that is in the direction towards other,
3144 unless both have the same value. If the two operands are
3145 numerically equal, then the result is a copy of self with the
3146 sign set to be the same as the sign of other.
3148 other = _convert_other(other, raiseit=True)
3150 if context is None:
3151 context = getcontext()
3153 ans = self._check_nans(other, context)
3154 if ans:
3155 return ans
3157 comparison = self.__cmp__(other)
3158 if comparison == 0:
3159 return self.copy_sign(other)
3161 if comparison == -1:
3162 ans = self.next_plus(context)
3163 else: # comparison == 1
3164 ans = self.next_minus(context)
3166 # decide which flags to raise using value of ans
3167 if ans._isinfinity():
3168 context._raise_error(Overflow,
3169 'Infinite result from next_toward',
3170 ans._sign)
3171 context._raise_error(Rounded)
3172 context._raise_error(Inexact)
3173 elif ans.adjusted() < context.Emin:
3174 context._raise_error(Underflow)
3175 context._raise_error(Subnormal)
3176 context._raise_error(Rounded)
3177 context._raise_error(Inexact)
3178 # if precision == 1 then we don't raise Clamped for a
3179 # result 0E-Etiny.
3180 if not ans:
3181 context._raise_error(Clamped)
3183 return ans
3185 def number_class(self, context=None):
3186 """Returns an indication of the class of self.
3188 The class is one of the following strings:
3189 sNaN
3191 -Infinity
3192 -Normal
3193 -Subnormal
3194 -Zero
3195 +Zero
3196 +Subnormal
3197 +Normal
3198 +Infinity
3200 if self.is_snan():
3201 return "sNaN"
3202 if self.is_qnan():
3203 return "NaN"
3204 inf = self._isinfinity()
3205 if inf == 1:
3206 return "+Infinity"
3207 if inf == -1:
3208 return "-Infinity"
3209 if self.is_zero():
3210 if self._sign:
3211 return "-Zero"
3212 else:
3213 return "+Zero"
3214 if context is None:
3215 context = getcontext()
3216 if self.is_subnormal(context=context):
3217 if self._sign:
3218 return "-Subnormal"
3219 else:
3220 return "+Subnormal"
3221 # just a normal, regular, boring number, :)
3222 if self._sign:
3223 return "-Normal"
3224 else:
3225 return "+Normal"
3227 def radix(self):
3228 """Just returns 10, as this is Decimal, :)"""
3229 return Decimal(10)
3231 def rotate(self, other, context=None):
3232 """Returns a rotated copy of self, value-of-other times."""
3233 if context is None:
3234 context = getcontext()
3236 ans = self._check_nans(other, context)
3237 if ans:
3238 return ans
3240 if other._exp != 0:
3241 return context._raise_error(InvalidOperation)
3242 if not (-context.prec <= int(other) <= context.prec):
3243 return context._raise_error(InvalidOperation)
3245 if self._isinfinity():
3246 return Decimal(self)
3248 # get values, pad if necessary
3249 torot = int(other)
3250 rotdig = self._int
3251 topad = context.prec - len(rotdig)
3252 if topad:
3253 rotdig = '0'*topad + rotdig
3255 # let's rotate!
3256 rotated = rotdig[torot:] + rotdig[:torot]
3257 return _dec_from_triple(self._sign,
3258 rotated.lstrip('0') or '0', self._exp)
3260 def scaleb (self, other, context=None):
3261 """Returns self operand after adding the second value to its exp."""
3262 if context is None:
3263 context = getcontext()
3265 ans = self._check_nans(other, context)
3266 if ans:
3267 return ans
3269 if other._exp != 0:
3270 return context._raise_error(InvalidOperation)
3271 liminf = -2 * (context.Emax + context.prec)
3272 limsup = 2 * (context.Emax + context.prec)
3273 if not (liminf <= int(other) <= limsup):
3274 return context._raise_error(InvalidOperation)
3276 if self._isinfinity():
3277 return Decimal(self)
3279 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3280 d = d._fix(context)
3281 return d
3283 def shift(self, other, context=None):
3284 """Returns a shifted copy of self, value-of-other times."""
3285 if context is None:
3286 context = getcontext()
3288 ans = self._check_nans(other, context)
3289 if ans:
3290 return ans
3292 if other._exp != 0:
3293 return context._raise_error(InvalidOperation)
3294 if not (-context.prec <= int(other) <= context.prec):
3295 return context._raise_error(InvalidOperation)
3297 if self._isinfinity():
3298 return Decimal(self)
3300 # get values, pad if necessary
3301 torot = int(other)
3302 if not torot:
3303 return Decimal(self)
3304 rotdig = self._int
3305 topad = context.prec - len(rotdig)
3306 if topad:
3307 rotdig = '0'*topad + rotdig
3309 # let's shift!
3310 if torot < 0:
3311 rotated = rotdig[:torot]
3312 else:
3313 rotated = rotdig + '0'*torot
3314 rotated = rotated[-context.prec:]
3316 return _dec_from_triple(self._sign,
3317 rotated.lstrip('0') or '0', self._exp)
3319 # Support for pickling, copy, and deepcopy
3320 def __reduce__(self):
3321 return (self.__class__, (str(self),))
3323 def __copy__(self):
3324 if type(self) == Decimal:
3325 return self # I'm immutable; therefore I am my own clone
3326 return self.__class__(str(self))
3328 def __deepcopy__(self, memo):
3329 if type(self) == Decimal:
3330 return self # My components are also immutable
3331 return self.__class__(str(self))
3333 def _dec_from_triple(sign, coefficient, exponent, special=False):
3334 """Create a decimal instance directly, without any validation,
3335 normalization (e.g. removal of leading zeros) or argument
3336 conversion.
3338 This function is for *internal use only*.
3341 self = object.__new__(Decimal)
3342 self._sign = sign
3343 self._int = coefficient
3344 self._exp = exponent
3345 self._is_special = special
3347 return self
3349 ##### Context class #######################################################
3352 # get rounding method function:
3353 rounding_functions = [name for name in Decimal.__dict__.keys()
3354 if name.startswith('_round_')]
3355 for name in rounding_functions:
3356 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3357 globalname = name[1:].upper()
3358 val = globals()[globalname]
3359 Decimal._pick_rounding_function[val] = name
3361 del name, val, globalname, rounding_functions
3363 class _ContextManager(object):
3364 """Context manager class to support localcontext().
3366 Sets a copy of the supplied context in __enter__() and restores
3367 the previous decimal context in __exit__()
3369 def __init__(self, new_context):
3370 self.new_context = new_context.copy()
3371 def __enter__(self):
3372 self.saved_context = getcontext()
3373 setcontext(self.new_context)
3374 return self.new_context
3375 def __exit__(self, t, v, tb):
3376 setcontext(self.saved_context)
3378 class Context(object):
3379 """Contains the context for a Decimal instance.
3381 Contains:
3382 prec - precision (for use in rounding, division, square roots..)
3383 rounding - rounding type (how you round)
3384 traps - If traps[exception] = 1, then the exception is
3385 raised when it is caused. Otherwise, a value is
3386 substituted in.
3387 flags - When an exception is caused, flags[exception] is incremented.
3388 (Whether or not the trap_enabler is set)
3389 Should be reset by user of Decimal instance.
3390 Emin - Minimum exponent
3391 Emax - Maximum exponent
3392 capitals - If 1, 1*10^1 is printed as 1E+1.
3393 If 0, printed as 1e1
3394 _clamp - If 1, change exponents if too high (Default 0)
3397 def __init__(self, prec=None, rounding=None,
3398 traps=None, flags=None,
3399 Emin=None, Emax=None,
3400 capitals=None, _clamp=0,
3401 _ignored_flags=None):
3402 if flags is None:
3403 flags = []
3404 if _ignored_flags is None:
3405 _ignored_flags = []
3406 if not isinstance(flags, dict):
3407 flags = dict([(s,s in flags) for s in _signals])
3408 del s
3409 if traps is not None and not isinstance(traps, dict):
3410 traps = dict([(s,s in traps) for s in _signals])
3411 del s
3412 for name, val in locals().items():
3413 if val is None:
3414 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3415 else:
3416 setattr(self, name, val)
3417 del self.self
3419 def __repr__(self):
3420 """Show the current context."""
3421 s = []
3422 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3423 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3424 % vars(self))
3425 names = [f.__name__ for f, v in self.flags.items() if v]
3426 s.append('flags=[' + ', '.join(names) + ']')
3427 names = [t.__name__ for t, v in self.traps.items() if v]
3428 s.append('traps=[' + ', '.join(names) + ']')
3429 return ', '.join(s) + ')'
3431 def clear_flags(self):
3432 """Reset all flags to zero"""
3433 for flag in self.flags:
3434 self.flags[flag] = 0
3436 def _shallow_copy(self):
3437 """Returns a shallow copy from self."""
3438 nc = Context(self.prec, self.rounding, self.traps,
3439 self.flags, self.Emin, self.Emax,
3440 self.capitals, self._clamp, self._ignored_flags)
3441 return nc
3443 def copy(self):
3444 """Returns a deep copy from self."""
3445 nc = Context(self.prec, self.rounding, self.traps.copy(),
3446 self.flags.copy(), self.Emin, self.Emax,
3447 self.capitals, self._clamp, self._ignored_flags)
3448 return nc
3449 __copy__ = copy
3451 def _raise_error(self, condition, explanation = None, *args):
3452 """Handles an error
3454 If the flag is in _ignored_flags, returns the default response.
3455 Otherwise, it increments the flag, then, if the corresponding
3456 trap_enabler is set, it reaises the exception. Otherwise, it returns
3457 the default value after incrementing the flag.
3459 error = _condition_map.get(condition, condition)
3460 if error in self._ignored_flags:
3461 # Don't touch the flag
3462 return error().handle(self, *args)
3464 self.flags[error] += 1
3465 if not self.traps[error]:
3466 # The errors define how to handle themselves.
3467 return condition().handle(self, *args)
3469 # Errors should only be risked on copies of the context
3470 # self._ignored_flags = []
3471 raise error, explanation
3473 def _ignore_all_flags(self):
3474 """Ignore all flags, if they are raised"""
3475 return self._ignore_flags(*_signals)
3477 def _ignore_flags(self, *flags):
3478 """Ignore the flags, if they are raised"""
3479 # Do not mutate-- This way, copies of a context leave the original
3480 # alone.
3481 self._ignored_flags = (self._ignored_flags + list(flags))
3482 return list(flags)
3484 def _regard_flags(self, *flags):
3485 """Stop ignoring the flags, if they are raised"""
3486 if flags and isinstance(flags[0], (tuple,list)):
3487 flags = flags[0]
3488 for flag in flags:
3489 self._ignored_flags.remove(flag)
3491 def __hash__(self):
3492 """A Context cannot be hashed."""
3493 # We inherit object.__hash__, so we must deny this explicitly
3494 raise TypeError("Cannot hash a Context.")
3496 def Etiny(self):
3497 """Returns Etiny (= Emin - prec + 1)"""
3498 return int(self.Emin - self.prec + 1)
3500 def Etop(self):
3501 """Returns maximum exponent (= Emax - prec + 1)"""
3502 return int(self.Emax - self.prec + 1)
3504 def _set_rounding(self, type):
3505 """Sets the rounding type.
3507 Sets the rounding type, and returns the current (previous)
3508 rounding type. Often used like:
3510 context = context.copy()
3511 # so you don't change the calling context
3512 # if an error occurs in the middle.
3513 rounding = context._set_rounding(ROUND_UP)
3514 val = self.__sub__(other, context=context)
3515 context._set_rounding(rounding)
3517 This will make it round up for that operation.
3519 rounding = self.rounding
3520 self.rounding= type
3521 return rounding
3523 def create_decimal(self, num='0'):
3524 """Creates a new Decimal instance but using self as context."""
3525 d = Decimal(num, context=self)
3526 if d._isnan() and len(d._int) > self.prec - self._clamp:
3527 return self._raise_error(ConversionSyntax,
3528 "diagnostic info too long in NaN")
3529 return d._fix(self)
3531 # Methods
3532 def abs(self, a):
3533 """Returns the absolute value of the operand.
3535 If the operand is negative, the result is the same as using the minus
3536 operation on the operand. Otherwise, the result is the same as using
3537 the plus operation on the operand.
3539 >>> ExtendedContext.abs(Decimal('2.1'))
3540 Decimal("2.1")
3541 >>> ExtendedContext.abs(Decimal('-100'))
3542 Decimal("100")
3543 >>> ExtendedContext.abs(Decimal('101.5'))
3544 Decimal("101.5")
3545 >>> ExtendedContext.abs(Decimal('-101.5'))
3546 Decimal("101.5")
3548 return a.__abs__(context=self)
3550 def add(self, a, b):
3551 """Return the sum of the two operands.
3553 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3554 Decimal("19.00")
3555 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3556 Decimal("1.02E+4")
3558 return a.__add__(b, context=self)
3560 def _apply(self, a):
3561 return str(a._fix(self))
3563 def canonical(self, a):
3564 """Returns the same Decimal object.
3566 As we do not have different encodings for the same number, the
3567 received object already is in its canonical form.
3569 >>> ExtendedContext.canonical(Decimal('2.50'))
3570 Decimal("2.50")
3572 return a.canonical(context=self)
3574 def compare(self, a, b):
3575 """Compares values numerically.
3577 If the signs of the operands differ, a value representing each operand
3578 ('-1' if the operand is less than zero, '0' if the operand is zero or
3579 negative zero, or '1' if the operand is greater than zero) is used in
3580 place of that operand for the comparison instead of the actual
3581 operand.
3583 The comparison is then effected by subtracting the second operand from
3584 the first and then returning a value according to the result of the
3585 subtraction: '-1' if the result is less than zero, '0' if the result is
3586 zero or negative zero, or '1' if the result is greater than zero.
3588 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3589 Decimal("-1")
3590 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3591 Decimal("0")
3592 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3593 Decimal("0")
3594 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3595 Decimal("1")
3596 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3597 Decimal("1")
3598 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3599 Decimal("-1")
3601 return a.compare(b, context=self)
3603 def compare_signal(self, a, b):
3604 """Compares the values of the two operands numerically.
3606 It's pretty much like compare(), but all NaNs signal, with signaling
3607 NaNs taking precedence over quiet NaNs.
3609 >>> c = ExtendedContext
3610 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3611 Decimal("-1")
3612 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3613 Decimal("0")
3614 >>> c.flags[InvalidOperation] = 0
3615 >>> print c.flags[InvalidOperation]
3617 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3618 Decimal("NaN")
3619 >>> print c.flags[InvalidOperation]
3621 >>> c.flags[InvalidOperation] = 0
3622 >>> print c.flags[InvalidOperation]
3624 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3625 Decimal("NaN")
3626 >>> print c.flags[InvalidOperation]
3629 return a.compare_signal(b, context=self)
3631 def compare_total(self, a, b):
3632 """Compares two operands using their abstract representation.
3634 This is not like the standard compare, which use their numerical
3635 value. Note that a total ordering is defined for all possible abstract
3636 representations.
3638 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3639 Decimal("-1")
3640 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3641 Decimal("-1")
3642 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3643 Decimal("-1")
3644 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3645 Decimal("0")
3646 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3647 Decimal("1")
3648 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3649 Decimal("-1")
3651 return a.compare_total(b)
3653 def compare_total_mag(self, a, b):
3654 """Compares two operands using their abstract representation ignoring sign.
3656 Like compare_total, but with operand's sign ignored and assumed to be 0.
3658 return a.compare_total_mag(b)
3660 def copy_abs(self, a):
3661 """Returns a copy of the operand with the sign set to 0.
3663 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3664 Decimal("2.1")
3665 >>> ExtendedContext.copy_abs(Decimal('-100'))
3666 Decimal("100")
3668 return a.copy_abs()
3670 def copy_decimal(self, a):
3671 """Returns a copy of the decimal objet.
3673 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3674 Decimal("2.1")
3675 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3676 Decimal("-1.00")
3678 return Decimal(a)
3680 def copy_negate(self, a):
3681 """Returns a copy of the operand with the sign inverted.
3683 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3684 Decimal("-101.5")
3685 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3686 Decimal("101.5")
3688 return a.copy_negate()
3690 def copy_sign(self, a, b):
3691 """Copies the second operand's sign to the first one.
3693 In detail, it returns a copy of the first operand with the sign
3694 equal to the sign of the second operand.
3696 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3697 Decimal("1.50")
3698 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3699 Decimal("1.50")
3700 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3701 Decimal("-1.50")
3702 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3703 Decimal("-1.50")
3705 return a.copy_sign(b)
3707 def divide(self, a, b):
3708 """Decimal division in a specified context.
3710 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3711 Decimal("0.333333333")
3712 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3713 Decimal("0.666666667")
3714 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3715 Decimal("2.5")
3716 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3717 Decimal("0.1")
3718 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3719 Decimal("1")
3720 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3721 Decimal("4.00")
3722 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3723 Decimal("1.20")
3724 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3725 Decimal("10")
3726 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3727 Decimal("1000")
3728 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3729 Decimal("1.20E+6")
3731 return a.__div__(b, context=self)
3733 def divide_int(self, a, b):
3734 """Divides two numbers and returns the integer part of the result.
3736 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3737 Decimal("0")
3738 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3739 Decimal("3")
3740 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3741 Decimal("3")
3743 return a.__floordiv__(b, context=self)
3745 def divmod(self, a, b):
3746 return a.__divmod__(b, context=self)
3748 def exp(self, a):
3749 """Returns e ** a.
3751 >>> c = ExtendedContext.copy()
3752 >>> c.Emin = -999
3753 >>> c.Emax = 999
3754 >>> c.exp(Decimal('-Infinity'))
3755 Decimal("0")
3756 >>> c.exp(Decimal('-1'))
3757 Decimal("0.367879441")
3758 >>> c.exp(Decimal('0'))
3759 Decimal("1")
3760 >>> c.exp(Decimal('1'))
3761 Decimal("2.71828183")
3762 >>> c.exp(Decimal('0.693147181'))
3763 Decimal("2.00000000")
3764 >>> c.exp(Decimal('+Infinity'))
3765 Decimal("Infinity")
3767 return a.exp(context=self)
3769 def fma(self, a, b, c):
3770 """Returns a multiplied by b, plus c.
3772 The first two operands are multiplied together, using multiply,
3773 the third operand is then added to the result of that
3774 multiplication, using add, all with only one final rounding.
3776 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3777 Decimal("22")
3778 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3779 Decimal("-8")
3780 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3781 Decimal("1.38435736E+12")
3783 return a.fma(b, c, context=self)
3785 def is_canonical(self, a):
3786 """Return True if the operand is canonical; otherwise return False.
3788 Currently, the encoding of a Decimal instance is always
3789 canonical, so this method returns True for any Decimal.
3791 >>> ExtendedContext.is_canonical(Decimal('2.50'))
3792 True
3794 return a.is_canonical()
3796 def is_finite(self, a):
3797 """Return True if the operand is finite; otherwise return False.
3799 A Decimal instance is considered finite if it is neither
3800 infinite nor a NaN.
3802 >>> ExtendedContext.is_finite(Decimal('2.50'))
3803 True
3804 >>> ExtendedContext.is_finite(Decimal('-0.3'))
3805 True
3806 >>> ExtendedContext.is_finite(Decimal('0'))
3807 True
3808 >>> ExtendedContext.is_finite(Decimal('Inf'))
3809 False
3810 >>> ExtendedContext.is_finite(Decimal('NaN'))
3811 False
3813 return a.is_finite()
3815 def is_infinite(self, a):
3816 """Return True if the operand is infinite; otherwise return False.
3818 >>> ExtendedContext.is_infinite(Decimal('2.50'))
3819 False
3820 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
3821 True
3822 >>> ExtendedContext.is_infinite(Decimal('NaN'))
3823 False
3825 return a.is_infinite()
3827 def is_nan(self, a):
3828 """Return True if the operand is a qNaN or sNaN;
3829 otherwise return False.
3831 >>> ExtendedContext.is_nan(Decimal('2.50'))
3832 False
3833 >>> ExtendedContext.is_nan(Decimal('NaN'))
3834 True
3835 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
3836 True
3838 return a.is_nan()
3840 def is_normal(self, a):
3841 """Return True if the operand is a normal number;
3842 otherwise return False.
3844 >>> c = ExtendedContext.copy()
3845 >>> c.Emin = -999
3846 >>> c.Emax = 999
3847 >>> c.is_normal(Decimal('2.50'))
3848 True
3849 >>> c.is_normal(Decimal('0.1E-999'))
3850 False
3851 >>> c.is_normal(Decimal('0.00'))
3852 False
3853 >>> c.is_normal(Decimal('-Inf'))
3854 False
3855 >>> c.is_normal(Decimal('NaN'))
3856 False
3858 return a.is_normal(context=self)
3860 def is_qnan(self, a):
3861 """Return True if the operand is a quiet NaN; otherwise return False.
3863 >>> ExtendedContext.is_qnan(Decimal('2.50'))
3864 False
3865 >>> ExtendedContext.is_qnan(Decimal('NaN'))
3866 True
3867 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
3868 False
3870 return a.is_qnan()
3872 def is_signed(self, a):
3873 """Return True if the operand is negative; otherwise return False.
3875 >>> ExtendedContext.is_signed(Decimal('2.50'))
3876 False
3877 >>> ExtendedContext.is_signed(Decimal('-12'))
3878 True
3879 >>> ExtendedContext.is_signed(Decimal('-0'))
3880 True
3882 return a.is_signed()
3884 def is_snan(self, a):
3885 """Return True if the operand is a signaling NaN;
3886 otherwise return False.
3888 >>> ExtendedContext.is_snan(Decimal('2.50'))
3889 False
3890 >>> ExtendedContext.is_snan(Decimal('NaN'))
3891 False
3892 >>> ExtendedContext.is_snan(Decimal('sNaN'))
3893 True
3895 return a.is_snan()
3897 def is_subnormal(self, a):
3898 """Return True if the operand is subnormal; otherwise return False.
3900 >>> c = ExtendedContext.copy()
3901 >>> c.Emin = -999
3902 >>> c.Emax = 999
3903 >>> c.is_subnormal(Decimal('2.50'))
3904 False
3905 >>> c.is_subnormal(Decimal('0.1E-999'))
3906 True
3907 >>> c.is_subnormal(Decimal('0.00'))
3908 False
3909 >>> c.is_subnormal(Decimal('-Inf'))
3910 False
3911 >>> c.is_subnormal(Decimal('NaN'))
3912 False
3914 return a.is_subnormal(context=self)
3916 def is_zero(self, a):
3917 """Return True if the operand is a zero; otherwise return False.
3919 >>> ExtendedContext.is_zero(Decimal('0'))
3920 True
3921 >>> ExtendedContext.is_zero(Decimal('2.50'))
3922 False
3923 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
3924 True
3926 return a.is_zero()
3928 def ln(self, a):
3929 """Returns the natural (base e) logarithm of the operand.
3931 >>> c = ExtendedContext.copy()
3932 >>> c.Emin = -999
3933 >>> c.Emax = 999
3934 >>> c.ln(Decimal('0'))
3935 Decimal("-Infinity")
3936 >>> c.ln(Decimal('1.000'))
3937 Decimal("0")
3938 >>> c.ln(Decimal('2.71828183'))
3939 Decimal("1.00000000")
3940 >>> c.ln(Decimal('10'))
3941 Decimal("2.30258509")
3942 >>> c.ln(Decimal('+Infinity'))
3943 Decimal("Infinity")
3945 return a.ln(context=self)
3947 def log10(self, a):
3948 """Returns the base 10 logarithm of the operand.
3950 >>> c = ExtendedContext.copy()
3951 >>> c.Emin = -999
3952 >>> c.Emax = 999
3953 >>> c.log10(Decimal('0'))
3954 Decimal("-Infinity")
3955 >>> c.log10(Decimal('0.001'))
3956 Decimal("-3")
3957 >>> c.log10(Decimal('1.000'))
3958 Decimal("0")
3959 >>> c.log10(Decimal('2'))
3960 Decimal("0.301029996")
3961 >>> c.log10(Decimal('10'))
3962 Decimal("1")
3963 >>> c.log10(Decimal('70'))
3964 Decimal("1.84509804")
3965 >>> c.log10(Decimal('+Infinity'))
3966 Decimal("Infinity")
3968 return a.log10(context=self)
3970 def logb(self, a):
3971 """ Returns the exponent of the magnitude of the operand's MSD.
3973 The result is the integer which is the exponent of the magnitude
3974 of the most significant digit of the operand (as though the
3975 operand were truncated to a single digit while maintaining the
3976 value of that digit and without limiting the resulting exponent).
3978 >>> ExtendedContext.logb(Decimal('250'))
3979 Decimal("2")
3980 >>> ExtendedContext.logb(Decimal('2.50'))
3981 Decimal("0")
3982 >>> ExtendedContext.logb(Decimal('0.03'))
3983 Decimal("-2")
3984 >>> ExtendedContext.logb(Decimal('0'))
3985 Decimal("-Infinity")
3987 return a.logb(context=self)
3989 def logical_and(self, a, b):
3990 """Applies the logical operation 'and' between each operand's digits.
3992 The operands must be both logical numbers.
3994 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
3995 Decimal("0")
3996 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
3997 Decimal("0")
3998 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
3999 Decimal("0")
4000 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4001 Decimal("1")
4002 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4003 Decimal("1000")
4004 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4005 Decimal("10")
4007 return a.logical_and(b, context=self)
4009 def logical_invert(self, a):
4010 """Invert all the digits in the operand.
4012 The operand must be a logical number.
4014 >>> ExtendedContext.logical_invert(Decimal('0'))
4015 Decimal("111111111")
4016 >>> ExtendedContext.logical_invert(Decimal('1'))
4017 Decimal("111111110")
4018 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4019 Decimal("0")
4020 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4021 Decimal("10101010")
4023 return a.logical_invert(context=self)
4025 def logical_or(self, a, b):
4026 """Applies the logical operation 'or' between each operand's digits.
4028 The operands must be both logical numbers.
4030 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4031 Decimal("0")
4032 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4033 Decimal("1")
4034 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4035 Decimal("1")
4036 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4037 Decimal("1")
4038 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4039 Decimal("1110")
4040 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4041 Decimal("1110")
4043 return a.logical_or(b, context=self)
4045 def logical_xor(self, a, b):
4046 """Applies the logical operation 'xor' between each operand's digits.
4048 The operands must be both logical numbers.
4050 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4051 Decimal("0")
4052 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4053 Decimal("1")
4054 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4055 Decimal("1")
4056 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4057 Decimal("0")
4058 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4059 Decimal("110")
4060 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4061 Decimal("1101")
4063 return a.logical_xor(b, context=self)
4065 def max(self, a,b):
4066 """max compares two values numerically and returns the maximum.
4068 If either operand is a NaN then the general rules apply.
4069 Otherwise, the operands are compared as as though by the compare
4070 operation. If they are numerically equal then the left-hand operand
4071 is chosen as the result. Otherwise the maximum (closer to positive
4072 infinity) of the two operands is chosen as the result.
4074 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4075 Decimal("3")
4076 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4077 Decimal("3")
4078 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4079 Decimal("1")
4080 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4081 Decimal("7")
4083 return a.max(b, context=self)
4085 def max_mag(self, a, b):
4086 """Compares the values numerically with their sign ignored."""
4087 return a.max_mag(b, context=self)
4089 def min(self, a,b):
4090 """min compares two values numerically and returns the minimum.
4092 If either operand is a NaN then the general rules apply.
4093 Otherwise, the operands are compared as as though by the compare
4094 operation. If they are numerically equal then the left-hand operand
4095 is chosen as the result. Otherwise the minimum (closer to negative
4096 infinity) of the two operands is chosen as the result.
4098 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4099 Decimal("2")
4100 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4101 Decimal("-10")
4102 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4103 Decimal("1.0")
4104 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4105 Decimal("7")
4107 return a.min(b, context=self)
4109 def min_mag(self, a, b):
4110 """Compares the values numerically with their sign ignored."""
4111 return a.min_mag(b, context=self)
4113 def minus(self, a):
4114 """Minus corresponds to unary prefix minus in Python.
4116 The operation is evaluated using the same rules as subtract; the
4117 operation minus(a) is calculated as subtract('0', a) where the '0'
4118 has the same exponent as the operand.
4120 >>> ExtendedContext.minus(Decimal('1.3'))
4121 Decimal("-1.3")
4122 >>> ExtendedContext.minus(Decimal('-1.3'))
4123 Decimal("1.3")
4125 return a.__neg__(context=self)
4127 def multiply(self, a, b):
4128 """multiply multiplies two operands.
4130 If either operand is a special value then the general rules apply.
4131 Otherwise, the operands are multiplied together ('long multiplication'),
4132 resulting in a number which may be as long as the sum of the lengths
4133 of the two operands.
4135 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4136 Decimal("3.60")
4137 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4138 Decimal("21")
4139 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4140 Decimal("0.72")
4141 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4142 Decimal("-0.0")
4143 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4144 Decimal("4.28135971E+11")
4146 return a.__mul__(b, context=self)
4148 def next_minus(self, a):
4149 """Returns the largest representable number smaller than a.
4151 >>> c = ExtendedContext.copy()
4152 >>> c.Emin = -999
4153 >>> c.Emax = 999
4154 >>> ExtendedContext.next_minus(Decimal('1'))
4155 Decimal("0.999999999")
4156 >>> c.next_minus(Decimal('1E-1007'))
4157 Decimal("0E-1007")
4158 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4159 Decimal("-1.00000004")
4160 >>> c.next_minus(Decimal('Infinity'))
4161 Decimal("9.99999999E+999")
4163 return a.next_minus(context=self)
4165 def next_plus(self, a):
4166 """Returns the smallest representable number larger than a.
4168 >>> c = ExtendedContext.copy()
4169 >>> c.Emin = -999
4170 >>> c.Emax = 999
4171 >>> ExtendedContext.next_plus(Decimal('1'))
4172 Decimal("1.00000001")
4173 >>> c.next_plus(Decimal('-1E-1007'))
4174 Decimal("-0E-1007")
4175 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4176 Decimal("-1.00000002")
4177 >>> c.next_plus(Decimal('-Infinity'))
4178 Decimal("-9.99999999E+999")
4180 return a.next_plus(context=self)
4182 def next_toward(self, a, b):
4183 """Returns the number closest to a, in direction towards b.
4185 The result is the closest representable number from the first
4186 operand (but not the first operand) that is in the direction
4187 towards the second operand, unless the operands have the same
4188 value.
4190 >>> c = ExtendedContext.copy()
4191 >>> c.Emin = -999
4192 >>> c.Emax = 999
4193 >>> c.next_toward(Decimal('1'), Decimal('2'))
4194 Decimal("1.00000001")
4195 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4196 Decimal("-0E-1007")
4197 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4198 Decimal("-1.00000002")
4199 >>> c.next_toward(Decimal('1'), Decimal('0'))
4200 Decimal("0.999999999")
4201 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4202 Decimal("0E-1007")
4203 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4204 Decimal("-1.00000004")
4205 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4206 Decimal("-0.00")
4208 return a.next_toward(b, context=self)
4210 def normalize(self, a):
4211 """normalize reduces an operand to its simplest form.
4213 Essentially a plus operation with all trailing zeros removed from the
4214 result.
4216 >>> ExtendedContext.normalize(Decimal('2.1'))
4217 Decimal("2.1")
4218 >>> ExtendedContext.normalize(Decimal('-2.0'))
4219 Decimal("-2")
4220 >>> ExtendedContext.normalize(Decimal('1.200'))
4221 Decimal("1.2")
4222 >>> ExtendedContext.normalize(Decimal('-120'))
4223 Decimal("-1.2E+2")
4224 >>> ExtendedContext.normalize(Decimal('120.00'))
4225 Decimal("1.2E+2")
4226 >>> ExtendedContext.normalize(Decimal('0.00'))
4227 Decimal("0")
4229 return a.normalize(context=self)
4231 def number_class(self, a):
4232 """Returns an indication of the class of the operand.
4234 The class is one of the following strings:
4235 -sNaN
4236 -NaN
4237 -Infinity
4238 -Normal
4239 -Subnormal
4240 -Zero
4241 +Zero
4242 +Subnormal
4243 +Normal
4244 +Infinity
4246 >>> c = Context(ExtendedContext)
4247 >>> c.Emin = -999
4248 >>> c.Emax = 999
4249 >>> c.number_class(Decimal('Infinity'))
4250 '+Infinity'
4251 >>> c.number_class(Decimal('1E-10'))
4252 '+Normal'
4253 >>> c.number_class(Decimal('2.50'))
4254 '+Normal'
4255 >>> c.number_class(Decimal('0.1E-999'))
4256 '+Subnormal'
4257 >>> c.number_class(Decimal('0'))
4258 '+Zero'
4259 >>> c.number_class(Decimal('-0'))
4260 '-Zero'
4261 >>> c.number_class(Decimal('-0.1E-999'))
4262 '-Subnormal'
4263 >>> c.number_class(Decimal('-1E-10'))
4264 '-Normal'
4265 >>> c.number_class(Decimal('-2.50'))
4266 '-Normal'
4267 >>> c.number_class(Decimal('-Infinity'))
4268 '-Infinity'
4269 >>> c.number_class(Decimal('NaN'))
4270 'NaN'
4271 >>> c.number_class(Decimal('-NaN'))
4272 'NaN'
4273 >>> c.number_class(Decimal('sNaN'))
4274 'sNaN'
4276 return a.number_class(context=self)
4278 def plus(self, a):
4279 """Plus corresponds to unary prefix plus in Python.
4281 The operation is evaluated using the same rules as add; the
4282 operation plus(a) is calculated as add('0', a) where the '0'
4283 has the same exponent as the operand.
4285 >>> ExtendedContext.plus(Decimal('1.3'))
4286 Decimal("1.3")
4287 >>> ExtendedContext.plus(Decimal('-1.3'))
4288 Decimal("-1.3")
4290 return a.__pos__(context=self)
4292 def power(self, a, b, modulo=None):
4293 """Raises a to the power of b, to modulo if given.
4295 With two arguments, compute a**b. If a is negative then b
4296 must be integral. The result will be inexact unless b is
4297 integral and the result is finite and can be expressed exactly
4298 in 'precision' digits.
4300 With three arguments, compute (a**b) % modulo. For the
4301 three argument form, the following restrictions on the
4302 arguments hold:
4304 - all three arguments must be integral
4305 - b must be nonnegative
4306 - at least one of a or b must be nonzero
4307 - modulo must be nonzero and have at most 'precision' digits
4309 The result of pow(a, b, modulo) is identical to the result
4310 that would be obtained by computing (a**b) % modulo with
4311 unbounded precision, but is computed more efficiently. It is
4312 always exact.
4314 >>> c = ExtendedContext.copy()
4315 >>> c.Emin = -999
4316 >>> c.Emax = 999
4317 >>> c.power(Decimal('2'), Decimal('3'))
4318 Decimal("8")
4319 >>> c.power(Decimal('-2'), Decimal('3'))
4320 Decimal("-8")
4321 >>> c.power(Decimal('2'), Decimal('-3'))
4322 Decimal("0.125")
4323 >>> c.power(Decimal('1.7'), Decimal('8'))
4324 Decimal("69.7575744")
4325 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4326 Decimal("2.00000000")
4327 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4328 Decimal("0")
4329 >>> c.power(Decimal('Infinity'), Decimal('0'))
4330 Decimal("1")
4331 >>> c.power(Decimal('Infinity'), Decimal('1'))
4332 Decimal("Infinity")
4333 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4334 Decimal("-0")
4335 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4336 Decimal("1")
4337 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4338 Decimal("-Infinity")
4339 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4340 Decimal("Infinity")
4341 >>> c.power(Decimal('0'), Decimal('0'))
4342 Decimal("NaN")
4344 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4345 Decimal("11")
4346 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4347 Decimal("-11")
4348 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4349 Decimal("1")
4350 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4351 Decimal("11")
4352 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4353 Decimal("11729830")
4354 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4355 Decimal("-0")
4356 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4357 Decimal("1")
4359 return a.__pow__(b, modulo, context=self)
4361 def quantize(self, a, b):
4362 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4364 The coefficient of the result is derived from that of the left-hand
4365 operand. It may be rounded using the current rounding setting (if the
4366 exponent is being increased), multiplied by a positive power of ten (if
4367 the exponent is being decreased), or is unchanged (if the exponent is
4368 already equal to that of the right-hand operand).
4370 Unlike other operations, if the length of the coefficient after the
4371 quantize operation would be greater than precision then an Invalid
4372 operation condition is raised. This guarantees that, unless there is
4373 an error condition, the exponent of the result of a quantize is always
4374 equal to that of the right-hand operand.
4376 Also unlike other operations, quantize will never raise Underflow, even
4377 if the result is subnormal and inexact.
4379 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4380 Decimal("2.170")
4381 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4382 Decimal("2.17")
4383 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4384 Decimal("2.2")
4385 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4386 Decimal("2")
4387 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4388 Decimal("0E+1")
4389 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4390 Decimal("-Infinity")
4391 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4392 Decimal("NaN")
4393 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4394 Decimal("-0")
4395 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4396 Decimal("-0E+5")
4397 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4398 Decimal("NaN")
4399 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4400 Decimal("NaN")
4401 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4402 Decimal("217.0")
4403 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4404 Decimal("217")
4405 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4406 Decimal("2.2E+2")
4407 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4408 Decimal("2E+2")
4410 return a.quantize(b, context=self)
4412 def radix(self):
4413 """Just returns 10, as this is Decimal, :)
4415 >>> ExtendedContext.radix()
4416 Decimal("10")
4418 return Decimal(10)
4420 def remainder(self, a, b):
4421 """Returns the remainder from integer division.
4423 The result is the residue of the dividend after the operation of
4424 calculating integer division as described for divide-integer, rounded
4425 to precision digits if necessary. The sign of the result, if
4426 non-zero, is the same as that of the original dividend.
4428 This operation will fail under the same conditions as integer division
4429 (that is, if integer division on the same two operands would fail, the
4430 remainder cannot be calculated).
4432 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4433 Decimal("2.1")
4434 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4435 Decimal("1")
4436 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4437 Decimal("-1")
4438 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4439 Decimal("0.2")
4440 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4441 Decimal("0.1")
4442 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4443 Decimal("1.0")
4445 return a.__mod__(b, context=self)
4447 def remainder_near(self, a, b):
4448 """Returns to be "a - b * n", where n is the integer nearest the exact
4449 value of "x / b" (if two integers are equally near then the even one
4450 is chosen). If the result is equal to 0 then its sign will be the
4451 sign of a.
4453 This operation will fail under the same conditions as integer division
4454 (that is, if integer division on the same two operands would fail, the
4455 remainder cannot be calculated).
4457 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4458 Decimal("-0.9")
4459 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4460 Decimal("-2")
4461 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4462 Decimal("1")
4463 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4464 Decimal("-1")
4465 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4466 Decimal("0.2")
4467 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4468 Decimal("0.1")
4469 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4470 Decimal("-0.3")
4472 return a.remainder_near(b, context=self)
4474 def rotate(self, a, b):
4475 """Returns a rotated copy of a, b times.
4477 The coefficient of the result is a rotated copy of the digits in
4478 the coefficient of the first operand. The number of places of
4479 rotation is taken from the absolute value of the second operand,
4480 with the rotation being to the left if the second operand is
4481 positive or to the right otherwise.
4483 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4484 Decimal("400000003")
4485 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4486 Decimal("12")
4487 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4488 Decimal("891234567")
4489 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4490 Decimal("123456789")
4491 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4492 Decimal("345678912")
4494 return a.rotate(b, context=self)
4496 def same_quantum(self, a, b):
4497 """Returns True if the two operands have the same exponent.
4499 The result is never affected by either the sign or the coefficient of
4500 either operand.
4502 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4503 False
4504 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4505 True
4506 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4507 False
4508 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4509 True
4511 return a.same_quantum(b)
4513 def scaleb (self, a, b):
4514 """Returns the first operand after adding the second value its exp.
4516 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4517 Decimal("0.0750")
4518 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4519 Decimal("7.50")
4520 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4521 Decimal("7.50E+3")
4523 return a.scaleb (b, context=self)
4525 def shift(self, a, b):
4526 """Returns a shifted copy of a, b times.
4528 The coefficient of the result is a shifted copy of the digits
4529 in the coefficient of the first operand. The number of places
4530 to shift is taken from the absolute value of the second operand,
4531 with the shift being to the left if the second operand is
4532 positive or to the right otherwise. Digits shifted into the
4533 coefficient are zeros.
4535 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4536 Decimal("400000000")
4537 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4538 Decimal("0")
4539 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4540 Decimal("1234567")
4541 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4542 Decimal("123456789")
4543 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4544 Decimal("345678900")
4546 return a.shift(b, context=self)
4548 def sqrt(self, a):
4549 """Square root of a non-negative number to context precision.
4551 If the result must be inexact, it is rounded using the round-half-even
4552 algorithm.
4554 >>> ExtendedContext.sqrt(Decimal('0'))
4555 Decimal("0")
4556 >>> ExtendedContext.sqrt(Decimal('-0'))
4557 Decimal("-0")
4558 >>> ExtendedContext.sqrt(Decimal('0.39'))
4559 Decimal("0.624499800")
4560 >>> ExtendedContext.sqrt(Decimal('100'))
4561 Decimal("10")
4562 >>> ExtendedContext.sqrt(Decimal('1'))
4563 Decimal("1")
4564 >>> ExtendedContext.sqrt(Decimal('1.0'))
4565 Decimal("1.0")
4566 >>> ExtendedContext.sqrt(Decimal('1.00'))
4567 Decimal("1.0")
4568 >>> ExtendedContext.sqrt(Decimal('7'))
4569 Decimal("2.64575131")
4570 >>> ExtendedContext.sqrt(Decimal('10'))
4571 Decimal("3.16227766")
4572 >>> ExtendedContext.prec
4575 return a.sqrt(context=self)
4577 def subtract(self, a, b):
4578 """Return the difference between the two operands.
4580 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4581 Decimal("0.23")
4582 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4583 Decimal("0.00")
4584 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4585 Decimal("-0.77")
4587 return a.__sub__(b, context=self)
4589 def to_eng_string(self, a):
4590 """Converts a number to a string, using scientific notation.
4592 The operation is not affected by the context.
4594 return a.to_eng_string(context=self)
4596 def to_sci_string(self, a):
4597 """Converts a number to a string, using scientific notation.
4599 The operation is not affected by the context.
4601 return a.__str__(context=self)
4603 def to_integral_exact(self, a):
4604 """Rounds to an integer.
4606 When the operand has a negative exponent, the result is the same
4607 as using the quantize() operation using the given operand as the
4608 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4609 of the operand as the precision setting; Inexact and Rounded flags
4610 are allowed in this operation. The rounding mode is taken from the
4611 context.
4613 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4614 Decimal("2")
4615 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4616 Decimal("100")
4617 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4618 Decimal("100")
4619 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4620 Decimal("102")
4621 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4622 Decimal("-102")
4623 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4624 Decimal("1.0E+6")
4625 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4626 Decimal("7.89E+77")
4627 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4628 Decimal("-Infinity")
4630 return a.to_integral_exact(context=self)
4632 def to_integral_value(self, a):
4633 """Rounds to an integer.
4635 When the operand has a negative exponent, the result is the same
4636 as using the quantize() operation using the given operand as the
4637 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4638 of the operand as the precision setting, except that no flags will
4639 be set. The rounding mode is taken from the context.
4641 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4642 Decimal("2")
4643 >>> ExtendedContext.to_integral_value(Decimal('100'))
4644 Decimal("100")
4645 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4646 Decimal("100")
4647 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4648 Decimal("102")
4649 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4650 Decimal("-102")
4651 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4652 Decimal("1.0E+6")
4653 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4654 Decimal("7.89E+77")
4655 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4656 Decimal("-Infinity")
4658 return a.to_integral_value(context=self)
4660 # the method name changed, but we provide also the old one, for compatibility
4661 to_integral = to_integral_value
4663 class _WorkRep(object):
4664 __slots__ = ('sign','int','exp')
4665 # sign: 0 or 1
4666 # int: int or long
4667 # exp: None, int, or string
4669 def __init__(self, value=None):
4670 if value is None:
4671 self.sign = None
4672 self.int = 0
4673 self.exp = None
4674 elif isinstance(value, Decimal):
4675 self.sign = value._sign
4676 self.int = int(value._int)
4677 self.exp = value._exp
4678 else:
4679 # assert isinstance(value, tuple)
4680 self.sign = value[0]
4681 self.int = value[1]
4682 self.exp = value[2]
4684 def __repr__(self):
4685 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4687 __str__ = __repr__
4691 def _normalize(op1, op2, prec = 0):
4692 """Normalizes op1, op2 to have the same exp and length of coefficient.
4694 Done during addition.
4696 if op1.exp < op2.exp:
4697 tmp = op2
4698 other = op1
4699 else:
4700 tmp = op1
4701 other = op2
4703 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4704 # Then adding 10**exp to tmp has the same effect (after rounding)
4705 # as adding any positive quantity smaller than 10**exp; similarly
4706 # for subtraction. So if other is smaller than 10**exp we replace
4707 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4708 tmp_len = len(str(tmp.int))
4709 other_len = len(str(other.int))
4710 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4711 if other_len + other.exp - 1 < exp:
4712 other.int = 1
4713 other.exp = exp
4715 tmp.int *= 10 ** (tmp.exp - other.exp)
4716 tmp.exp = other.exp
4717 return op1, op2
4719 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4721 # This function from Tim Peters was taken from here:
4722 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4723 # The correction being in the function definition is for speed, and
4724 # the whole function is not resolved with math.log because of avoiding
4725 # the use of floats.
4726 def _nbits(n, correction = {
4727 '0': 4, '1': 3, '2': 2, '3': 2,
4728 '4': 1, '5': 1, '6': 1, '7': 1,
4729 '8': 0, '9': 0, 'a': 0, 'b': 0,
4730 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4731 """Number of bits in binary representation of the positive integer n,
4732 or 0 if n == 0.
4734 if n < 0:
4735 raise ValueError("The argument to _nbits should be nonnegative.")
4736 hex_n = "%x" % n
4737 return 4*len(hex_n) - correction[hex_n[0]]
4739 def _sqrt_nearest(n, a):
4740 """Closest integer to the square root of the positive integer n. a is
4741 an initial approximation to the square root. Any positive integer
4742 will do for a, but the closer a is to the square root of n the
4743 faster convergence will be.
4746 if n <= 0 or a <= 0:
4747 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4750 while a != b:
4751 b, a = a, a--n//a>>1
4752 return a
4754 def _rshift_nearest(x, shift):
4755 """Given an integer x and a nonnegative integer shift, return closest
4756 integer to x / 2**shift; use round-to-even in case of a tie.
4759 b, q = 1L << shift, x >> shift
4760 return q + (2*(x & (b-1)) + (q&1) > b)
4762 def _div_nearest(a, b):
4763 """Closest integer to a/b, a and b positive integers; rounds to even
4764 in the case of a tie.
4767 q, r = divmod(a, b)
4768 return q + (2*r + (q&1) > b)
4770 def _ilog(x, M, L = 8):
4771 """Integer approximation to M*log(x/M), with absolute error boundable
4772 in terms only of x/M.
4774 Given positive integers x and M, return an integer approximation to
4775 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4776 between the approximation and the exact result is at most 22. For
4777 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4778 both cases these are upper bounds on the error; it will usually be
4779 much smaller."""
4781 # The basic algorithm is the following: let log1p be the function
4782 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
4783 # the reduction
4785 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
4787 # repeatedly until the argument to log1p is small (< 2**-L in
4788 # absolute value). For small y we can use the Taylor series
4789 # expansion
4791 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
4793 # truncating at T such that y**T is small enough. The whole
4794 # computation is carried out in a form of fixed-point arithmetic,
4795 # with a real number z being represented by an integer
4796 # approximation to z*M. To avoid loss of precision, the y below
4797 # is actually an integer approximation to 2**R*y*M, where R is the
4798 # number of reductions performed so far.
4800 y = x-M
4801 # argument reduction; R = number of reductions performed
4802 R = 0
4803 while (R <= L and long(abs(y)) << L-R >= M or
4804 R > L and abs(y) >> R-L >= M):
4805 y = _div_nearest(long(M*y) << 1,
4806 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
4807 R += 1
4809 # Taylor series with T terms
4810 T = -int(-10*len(str(M))//(3*L))
4811 yshift = _rshift_nearest(y, R)
4812 w = _div_nearest(M, T)
4813 for k in xrange(T-1, 0, -1):
4814 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
4816 return _div_nearest(w*y, M)
4818 def _dlog10(c, e, p):
4819 """Given integers c, e and p with c > 0, p >= 0, compute an integer
4820 approximation to 10**p * log10(c*10**e), with an absolute error of
4821 at most 1. Assumes that c*10**e is not exactly 1."""
4823 # increase precision by 2; compensate for this by dividing
4824 # final result by 100
4825 p += 2
4827 # write c*10**e as d*10**f with either:
4828 # f >= 0 and 1 <= d <= 10, or
4829 # f <= 0 and 0.1 <= d <= 1.
4830 # Thus for c*10**e close to 1, f = 0
4831 l = len(str(c))
4832 f = e+l - (e+l >= 1)
4834 if p > 0:
4835 M = 10**p
4836 k = e+p-f
4837 if k >= 0:
4838 c *= 10**k
4839 else:
4840 c = _div_nearest(c, 10**-k)
4842 log_d = _ilog(c, M) # error < 5 + 22 = 27
4843 log_10 = _log10_digits(p) # error < 1
4844 log_d = _div_nearest(log_d*M, log_10)
4845 log_tenpower = f*M # exact
4846 else:
4847 log_d = 0 # error < 2.31
4848 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
4850 return _div_nearest(log_tenpower+log_d, 100)
4852 def _dlog(c, e, p):
4853 """Given integers c, e and p with c > 0, compute an integer
4854 approximation to 10**p * log(c*10**e), with an absolute error of
4855 at most 1. Assumes that c*10**e is not exactly 1."""
4857 # Increase precision by 2. The precision increase is compensated
4858 # for at the end with a division by 100.
4859 p += 2
4861 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
4862 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
4863 # as 10**p * log(d) + 10**p*f * log(10).
4864 l = len(str(c))
4865 f = e+l - (e+l >= 1)
4867 # compute approximation to 10**p*log(d), with error < 27
4868 if p > 0:
4869 k = e+p-f
4870 if k >= 0:
4871 c *= 10**k
4872 else:
4873 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
4875 # _ilog magnifies existing error in c by a factor of at most 10
4876 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
4877 else:
4878 # p <= 0: just approximate the whole thing by 0; error < 2.31
4879 log_d = 0
4881 # compute approximation to f*10**p*log(10), with error < 11.
4882 if f:
4883 extra = len(str(abs(f)))-1
4884 if p + extra >= 0:
4885 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
4886 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
4887 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
4888 else:
4889 f_log_ten = 0
4890 else:
4891 f_log_ten = 0
4893 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
4894 return _div_nearest(f_log_ten + log_d, 100)
4896 class _Log10Memoize(object):
4897 """Class to compute, store, and allow retrieval of, digits of the
4898 constant log(10) = 2.302585.... This constant is needed by
4899 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
4900 def __init__(self):
4901 self.digits = "23025850929940456840179914546843642076011014886"
4903 def getdigits(self, p):
4904 """Given an integer p >= 0, return floor(10**p)*log(10).
4906 For example, self.getdigits(3) returns 2302.
4908 # digits are stored as a string, for quick conversion to
4909 # integer in the case that we've already computed enough
4910 # digits; the stored digits should always be correct
4911 # (truncated, not rounded to nearest).
4912 if p < 0:
4913 raise ValueError("p should be nonnegative")
4915 if p >= len(self.digits):
4916 # compute p+3, p+6, p+9, ... digits; continue until at
4917 # least one of the extra digits is nonzero
4918 extra = 3
4919 while True:
4920 # compute p+extra digits, correct to within 1ulp
4921 M = 10**(p+extra+2)
4922 digits = str(_div_nearest(_ilog(10*M, M), 100))
4923 if digits[-extra:] != '0'*extra:
4924 break
4925 extra += 3
4926 # keep all reliable digits so far; remove trailing zeros
4927 # and next nonzero digit
4928 self.digits = digits.rstrip('0')[:-1]
4929 return int(self.digits[:p+1])
4931 _log10_digits = _Log10Memoize().getdigits
4933 def _iexp(x, M, L=8):
4934 """Given integers x and M, M > 0, such that x/M is small in absolute
4935 value, compute an integer approximation to M*exp(x/M). For 0 <=
4936 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
4937 is usually much smaller)."""
4939 # Algorithm: to compute exp(z) for a real number z, first divide z
4940 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
4941 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
4942 # series
4944 # expm1(x) = x + x**2/2! + x**3/3! + ...
4946 # Now use the identity
4948 # expm1(2x) = expm1(x)*(expm1(x)+2)
4950 # R times to compute the sequence expm1(z/2**R),
4951 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
4953 # Find R such that x/2**R/M <= 2**-L
4954 R = _nbits((long(x)<<L)//M)
4956 # Taylor series. (2**L)**T > M
4957 T = -int(-10*len(str(M))//(3*L))
4958 y = _div_nearest(x, T)
4959 Mshift = long(M)<<R
4960 for i in xrange(T-1, 0, -1):
4961 y = _div_nearest(x*(Mshift + y), Mshift * i)
4963 # Expansion
4964 for k in xrange(R-1, -1, -1):
4965 Mshift = long(M)<<(k+2)
4966 y = _div_nearest(y*(y+Mshift), Mshift)
4968 return M+y
4970 def _dexp(c, e, p):
4971 """Compute an approximation to exp(c*10**e), with p decimal places of
4972 precision.
4974 Returns integers d, f such that:
4976 10**(p-1) <= d <= 10**p, and
4977 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
4979 In other words, d*10**f is an approximation to exp(c*10**e) with p
4980 digits of precision, and with an error in d of at most 1. This is
4981 almost, but not quite, the same as the error being < 1ulp: when d
4982 = 10**(p-1) the error could be up to 10 ulp."""
4984 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
4985 p += 2
4987 # compute log(10) with extra precision = adjusted exponent of c*10**e
4988 extra = max(0, e + len(str(c)) - 1)
4989 q = p + extra
4991 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
4992 # rounding down
4993 shift = e+q
4994 if shift >= 0:
4995 cshift = c*10**shift
4996 else:
4997 cshift = c//10**-shift
4998 quot, rem = divmod(cshift, _log10_digits(q))
5000 # reduce remainder back to original precision
5001 rem = _div_nearest(rem, 10**extra)
5003 # error in result of _iexp < 120; error after division < 0.62
5004 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5006 def _dpower(xc, xe, yc, ye, p):
5007 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5008 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5010 10**(p-1) <= c <= 10**p, and
5011 (c-1)*10**e < x**y < (c+1)*10**e
5013 in other words, c*10**e is an approximation to x**y with p digits
5014 of precision, and with an error in c of at most 1. (This is
5015 almost, but not quite, the same as the error being < 1ulp: when c
5016 == 10**(p-1) we can only guarantee error < 10ulp.)
5018 We assume that: x is positive and not equal to 1, and y is nonzero.
5021 # Find b such that 10**(b-1) <= |y| <= 10**b
5022 b = len(str(abs(yc))) + ye
5024 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5025 lxc = _dlog(xc, xe, p+b+1)
5027 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5028 shift = ye-b
5029 if shift >= 0:
5030 pc = lxc*yc*10**shift
5031 else:
5032 pc = _div_nearest(lxc*yc, 10**-shift)
5034 if pc == 0:
5035 # we prefer a result that isn't exactly 1; this makes it
5036 # easier to compute a correctly rounded result in __pow__
5037 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5038 coeff, exp = 10**(p-1)+1, 1-p
5039 else:
5040 coeff, exp = 10**p-1, -p
5041 else:
5042 coeff, exp = _dexp(pc, -(p+1), p+1)
5043 coeff = _div_nearest(coeff, 10)
5044 exp += 1
5046 return coeff, exp
5048 def _log10_lb(c, correction = {
5049 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5050 '6': 23, '7': 16, '8': 10, '9': 5}):
5051 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5052 if c <= 0:
5053 raise ValueError("The argument to _log10_lb should be nonnegative.")
5054 str_c = str(c)
5055 return 100*len(str_c) - correction[str_c[0]]
5057 ##### Helper Functions ####################################################
5059 def _convert_other(other, raiseit=False):
5060 """Convert other to Decimal.
5062 Verifies that it's ok to use in an implicit construction.
5064 if isinstance(other, Decimal):
5065 return other
5066 if isinstance(other, (int, long)):
5067 return Decimal(other)
5068 if raiseit:
5069 raise TypeError("Unable to convert %s to Decimal" % other)
5070 return NotImplemented
5072 ##### Setup Specific Contexts ############################################
5074 # The default context prototype used by Context()
5075 # Is mutable, so that new contexts can have different default values
5077 DefaultContext = Context(
5078 prec=28, rounding=ROUND_HALF_EVEN,
5079 traps=[DivisionByZero, Overflow, InvalidOperation],
5080 flags=[],
5081 Emax=999999999,
5082 Emin=-999999999,
5083 capitals=1
5086 # Pre-made alternate contexts offered by the specification
5087 # Don't change these; the user should be able to select these
5088 # contexts and be able to reproduce results from other implementations
5089 # of the spec.
5091 BasicContext = Context(
5092 prec=9, rounding=ROUND_HALF_UP,
5093 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5094 flags=[],
5097 ExtendedContext = Context(
5098 prec=9, rounding=ROUND_HALF_EVEN,
5099 traps=[],
5100 flags=[],
5104 ##### crud for parsing strings #############################################
5105 import re
5107 # Regular expression used for parsing numeric strings. Additional
5108 # comments:
5110 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5111 # whitespace. But note that the specification disallows whitespace in
5112 # a numeric string.
5114 # 2. For finite numbers (not infinities and NaNs) the body of the
5115 # number between the optional sign and the optional exponent must have
5116 # at least one decimal digit, possibly after the decimal point. The
5117 # lookahead expression '(?=\d|\.\d)' checks this.
5119 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5120 # other meaning for \d than the numbers [0-9].
5122 import re
5123 _parser = re.compile(r""" # A numeric string consists of:
5124 # \s*
5125 (?P<sign>[-+])? # an optional sign, followed by either...
5127 (?=\d|\.\d) # ...a number (with at least one digit)
5128 (?P<int>\d*) # consisting of a (possibly empty) integer part
5129 (\.(?P<frac>\d*))? # followed by an optional fractional part
5130 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5132 Inf(inity)? # ...an infinity, or...
5134 (?P<signal>s)? # ...an (optionally signaling)
5135 NaN # NaN
5136 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5138 # \s*
5140 """, re.VERBOSE | re.IGNORECASE).match
5142 _all_zeros = re.compile('0*$').match
5143 _exact_half = re.compile('50*$').match
5144 del re
5147 ##### Useful Constants (internal use only) ################################
5149 # Reusable defaults
5150 Inf = Decimal('Inf')
5151 negInf = Decimal('-Inf')
5152 NaN = Decimal('NaN')
5153 Dec_0 = Decimal(0)
5154 Dec_p1 = Decimal(1)
5155 Dec_n1 = Decimal(-1)
5157 # Infsign[sign] is infinity w/ that sign
5158 Infsign = (Inf, negInf)
5162 if __name__ == '__main__':
5163 import doctest, sys
5164 doctest.testmod(sys.modules[__name__])