UserString.MutableString has been removed in Python 3.0.
[python.git] / Lib / decimal.py
blob940a9d24d44c007f1bdafd88495f31e596d5cd60
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 try:
140 from collections import namedtuple as _namedtuple
141 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
142 except ImportError:
143 DecimalTuple = lambda *args: args
145 # Rounding
146 ROUND_DOWN = 'ROUND_DOWN'
147 ROUND_HALF_UP = 'ROUND_HALF_UP'
148 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
149 ROUND_CEILING = 'ROUND_CEILING'
150 ROUND_FLOOR = 'ROUND_FLOOR'
151 ROUND_UP = 'ROUND_UP'
152 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
153 ROUND_05UP = 'ROUND_05UP'
155 # Errors
157 class DecimalException(ArithmeticError):
158 """Base exception class.
160 Used exceptions derive from this.
161 If an exception derives from another exception besides this (such as
162 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
163 called if the others are present. This isn't actually used for
164 anything, though.
166 handle -- Called when context._raise_error is called and the
167 trap_enabler is set. First argument is self, second is the
168 context. More arguments can be given, those being after
169 the explanation in _raise_error (For example,
170 context._raise_error(NewError, '(-x)!', self._sign) would
171 call NewError().handle(context, self._sign).)
173 To define a new exception, it should be sufficient to have it derive
174 from DecimalException.
176 def handle(self, context, *args):
177 pass
180 class Clamped(DecimalException):
181 """Exponent of a 0 changed to fit bounds.
183 This occurs and signals clamped if the exponent of a result has been
184 altered in order to fit the constraints of a specific concrete
185 representation. This may occur when the exponent of a zero result would
186 be outside the bounds of a representation, or when a large normal
187 number would have an encoded exponent that cannot be represented. In
188 this latter case, the exponent is reduced to fit and the corresponding
189 number of zero digits are appended to the coefficient ("fold-down").
192 class InvalidOperation(DecimalException):
193 """An invalid operation was performed.
195 Various bad things cause this:
197 Something creates a signaling NaN
198 -INF + INF
199 0 * (+-)INF
200 (+-)INF / (+-)INF
201 x % 0
202 (+-)INF % x
203 x._rescale( non-integer )
204 sqrt(-x) , x > 0
205 0 ** 0
206 x ** (non-integer)
207 x ** (+-)INF
208 An operand is invalid
210 The result of the operation after these is a quiet positive NaN,
211 except when the cause is a signaling NaN, in which case the result is
212 also a quiet NaN, but with the original sign, and an optional
213 diagnostic information.
215 def handle(self, context, *args):
216 if args:
217 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
218 return ans._fix_nan(context)
219 return NaN
221 class ConversionSyntax(InvalidOperation):
222 """Trying to convert badly formed string.
224 This occurs and signals invalid-operation if an string is being
225 converted to a number and it does not conform to the numeric string
226 syntax. The result is [0,qNaN].
228 def handle(self, context, *args):
229 return NaN
231 class DivisionByZero(DecimalException, ZeroDivisionError):
232 """Division by 0.
234 This occurs and signals division-by-zero if division of a finite number
235 by zero was attempted (during a divide-integer or divide operation, or a
236 power operation with negative right-hand operand), and the dividend was
237 not zero.
239 The result of the operation is [sign,inf], where sign is the exclusive
240 or of the signs of the operands for divide, or is 1 for an odd power of
241 -0, for power.
244 def handle(self, context, sign, *args):
245 return Infsign[sign]
247 class DivisionImpossible(InvalidOperation):
248 """Cannot perform the division adequately.
250 This occurs and signals invalid-operation if the integer result of a
251 divide-integer or remainder operation had too many digits (would be
252 longer than precision). The result is [0,qNaN].
255 def handle(self, context, *args):
256 return NaN
258 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
259 """Undefined result of division.
261 This occurs and signals invalid-operation if division by zero was
262 attempted (during a divide-integer, divide, or remainder operation), and
263 the dividend is also zero. The result is [0,qNaN].
266 def handle(self, context, *args):
267 return NaN
269 class Inexact(DecimalException):
270 """Had to round, losing information.
272 This occurs and signals inexact whenever the result of an operation is
273 not exact (that is, it needed to be rounded and any discarded digits
274 were non-zero), or if an overflow or underflow condition occurs. The
275 result in all cases is unchanged.
277 The inexact signal may be tested (or trapped) to determine if a given
278 operation (or sequence of operations) was inexact.
281 class InvalidContext(InvalidOperation):
282 """Invalid context. Unknown rounding, for example.
284 This occurs and signals invalid-operation if an invalid context was
285 detected during an operation. This can occur if contexts are not checked
286 on creation and either the precision exceeds the capability of the
287 underlying concrete representation or an unknown or unsupported rounding
288 was specified. These aspects of the context need only be checked when
289 the values are required to be used. The result is [0,qNaN].
292 def handle(self, context, *args):
293 return NaN
295 class Rounded(DecimalException):
296 """Number got rounded (not necessarily changed during rounding).
298 This occurs and signals rounded whenever the result of an operation is
299 rounded (that is, some zero or non-zero digits were discarded from the
300 coefficient), or if an overflow or underflow condition occurs. The
301 result in all cases is unchanged.
303 The rounded signal may be tested (or trapped) to determine if a given
304 operation (or sequence of operations) caused a loss of precision.
307 class Subnormal(DecimalException):
308 """Exponent < Emin before rounding.
310 This occurs and signals subnormal whenever the result of a conversion or
311 operation is subnormal (that is, its adjusted exponent is less than
312 Emin, before any rounding). The result in all cases is unchanged.
314 The subnormal signal may be tested (or trapped) to determine if a given
315 or operation (or sequence of operations) yielded a subnormal result.
318 class Overflow(Inexact, Rounded):
319 """Numerical overflow.
321 This occurs and signals overflow if the adjusted exponent of a result
322 (from a conversion or from an operation that is not an attempt to divide
323 by zero), after rounding, would be greater than the largest value that
324 can be handled by the implementation (the value Emax).
326 The result depends on the rounding mode:
328 For round-half-up and round-half-even (and for round-half-down and
329 round-up, if implemented), the result of the operation is [sign,inf],
330 where sign is the sign of the intermediate result. For round-down, the
331 result is the largest finite number that can be represented in the
332 current precision, with the sign of the intermediate result. For
333 round-ceiling, the result is the same as for round-down if the sign of
334 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
335 the result is the same as for round-down if the sign of the intermediate
336 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
337 will also be raised.
340 def handle(self, context, sign, *args):
341 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
342 ROUND_HALF_DOWN, ROUND_UP):
343 return Infsign[sign]
344 if sign == 0:
345 if context.rounding == ROUND_CEILING:
346 return Infsign[sign]
347 return _dec_from_triple(sign, '9'*context.prec,
348 context.Emax-context.prec+1)
349 if sign == 1:
350 if context.rounding == ROUND_FLOOR:
351 return Infsign[sign]
352 return _dec_from_triple(sign, '9'*context.prec,
353 context.Emax-context.prec+1)
356 class Underflow(Inexact, Rounded, Subnormal):
357 """Numerical underflow with result rounded to 0.
359 This occurs and signals underflow if a result is inexact and the
360 adjusted exponent of the result would be smaller (more negative) than
361 the smallest value that can be handled by the implementation (the value
362 Emin). That is, the result is both inexact and subnormal.
364 The result after an underflow will be a subnormal number rounded, if
365 necessary, so that its exponent is not less than Etiny. This may result
366 in 0 with the sign of the intermediate result and an exponent of Etiny.
368 In all cases, Inexact, Rounded, and Subnormal will also be raised.
371 # List of public traps and flags
372 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
373 Underflow, InvalidOperation, Subnormal]
375 # Map conditions (per the spec) to signals
376 _condition_map = {ConversionSyntax:InvalidOperation,
377 DivisionImpossible:InvalidOperation,
378 DivisionUndefined:InvalidOperation,
379 InvalidContext:InvalidOperation}
381 ##### Context Functions ##################################################
383 # The getcontext() and setcontext() function manage access to a thread-local
384 # current context. Py2.4 offers direct support for thread locals. If that
385 # is not available, use threading.currentThread() which is slower but will
386 # work for older Pythons. If threads are not part of the build, create a
387 # mock threading object with threading.local() returning the module namespace.
389 try:
390 import threading
391 except ImportError:
392 # Python was compiled without threads; create a mock object instead
393 import sys
394 class MockThreading(object):
395 def local(self, sys=sys):
396 return sys.modules[__name__]
397 threading = MockThreading()
398 del sys, MockThreading
400 try:
401 threading.local
403 except AttributeError:
405 # To fix reloading, force it to create a new context
406 # Old contexts have different exceptions in their dicts, making problems.
407 if hasattr(threading.currentThread(), '__decimal_context__'):
408 del threading.currentThread().__decimal_context__
410 def setcontext(context):
411 """Set this thread's context to context."""
412 if context in (DefaultContext, BasicContext, ExtendedContext):
413 context = context.copy()
414 context.clear_flags()
415 threading.currentThread().__decimal_context__ = context
417 def getcontext():
418 """Returns this thread's context.
420 If this thread does not yet have a context, returns
421 a new context and sets this thread's context.
422 New contexts are copies of DefaultContext.
424 try:
425 return threading.currentThread().__decimal_context__
426 except AttributeError:
427 context = Context()
428 threading.currentThread().__decimal_context__ = context
429 return context
431 else:
433 local = threading.local()
434 if hasattr(local, '__decimal_context__'):
435 del local.__decimal_context__
437 def getcontext(_local=local):
438 """Returns this thread's context.
440 If this thread does not yet have a context, returns
441 a new context and sets this thread's context.
442 New contexts are copies of DefaultContext.
444 try:
445 return _local.__decimal_context__
446 except AttributeError:
447 context = Context()
448 _local.__decimal_context__ = context
449 return context
451 def setcontext(context, _local=local):
452 """Set this thread's context to context."""
453 if context in (DefaultContext, BasicContext, ExtendedContext):
454 context = context.copy()
455 context.clear_flags()
456 _local.__decimal_context__ = context
458 del threading, local # Don't contaminate the namespace
460 def localcontext(ctx=None):
461 """Return a context manager for a copy of the supplied context
463 Uses a copy of the current context if no context is specified
464 The returned context manager creates a local decimal context
465 in a with statement:
466 def sin(x):
467 with localcontext() as ctx:
468 ctx.prec += 2
469 # Rest of sin calculation algorithm
470 # uses a precision 2 greater than normal
471 return +s # Convert result to normal precision
473 def sin(x):
474 with localcontext(ExtendedContext):
475 # Rest of sin calculation algorithm
476 # uses the Extended Context from the
477 # General Decimal Arithmetic Specification
478 return +s # Convert result to normal context
480 >>> setcontext(DefaultContext)
481 >>> print getcontext().prec
483 >>> with localcontext():
484 ... ctx = getcontext()
485 ... ctx.prec += 2
486 ... print ctx.prec
489 >>> with localcontext(ExtendedContext):
490 ... print getcontext().prec
493 >>> print getcontext().prec
496 if ctx is None: ctx = getcontext()
497 return _ContextManager(ctx)
500 ##### Decimal class #######################################################
502 class Decimal(object):
503 """Floating point class for decimal arithmetic."""
505 __slots__ = ('_exp','_int','_sign', '_is_special')
506 # Generally, the value of the Decimal instance is given by
507 # (-1)**_sign * _int * 10**_exp
508 # Special values are signified by _is_special == True
510 # We're immutable, so use __new__ not __init__
511 def __new__(cls, value="0", context=None):
512 """Create a decimal point instance.
514 >>> Decimal('3.14') # string input
515 Decimal('3.14')
516 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
517 Decimal('3.14')
518 >>> Decimal(314) # int or long
519 Decimal('314')
520 >>> Decimal(Decimal(314)) # another decimal instance
521 Decimal('314')
522 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
523 Decimal('3.14')
526 # Note that the coefficient, self._int, is actually stored as
527 # a string rather than as a tuple of digits. This speeds up
528 # the "digits to integer" and "integer to digits" conversions
529 # that are used in almost every arithmetic operation on
530 # Decimals. This is an internal detail: the as_tuple function
531 # and the Decimal constructor still deal with tuples of
532 # digits.
534 self = object.__new__(cls)
536 # From a string
537 # REs insist on real strings, so we can too.
538 if isinstance(value, basestring):
539 m = _parser(value.strip())
540 if m is None:
541 if context is None:
542 context = getcontext()
543 return context._raise_error(ConversionSyntax,
544 "Invalid literal for Decimal: %r" % value)
546 if m.group('sign') == "-":
547 self._sign = 1
548 else:
549 self._sign = 0
550 intpart = m.group('int')
551 if intpart is not None:
552 # finite number
553 fracpart = m.group('frac')
554 exp = int(m.group('exp') or '0')
555 if fracpart is not None:
556 self._int = str((intpart+fracpart).lstrip('0') or '0')
557 self._exp = exp - len(fracpart)
558 else:
559 self._int = str(intpart.lstrip('0') or '0')
560 self._exp = exp
561 self._is_special = False
562 else:
563 diag = m.group('diag')
564 if diag is not None:
565 # NaN
566 self._int = str(diag.lstrip('0'))
567 if m.group('signal'):
568 self._exp = 'N'
569 else:
570 self._exp = 'n'
571 else:
572 # infinity
573 self._int = '0'
574 self._exp = 'F'
575 self._is_special = True
576 return self
578 # From an integer
579 if isinstance(value, (int,long)):
580 if value >= 0:
581 self._sign = 0
582 else:
583 self._sign = 1
584 self._exp = 0
585 self._int = str(abs(value))
586 self._is_special = False
587 return self
589 # From another decimal
590 if isinstance(value, Decimal):
591 self._exp = value._exp
592 self._sign = value._sign
593 self._int = value._int
594 self._is_special = value._is_special
595 return self
597 # From an internal working value
598 if isinstance(value, _WorkRep):
599 self._sign = value.sign
600 self._int = str(value.int)
601 self._exp = int(value.exp)
602 self._is_special = False
603 return self
605 # tuple/list conversion (possibly from as_tuple())
606 if isinstance(value, (list,tuple)):
607 if len(value) != 3:
608 raise ValueError('Invalid tuple size in creation of Decimal '
609 'from list or tuple. The list or tuple '
610 'should have exactly three elements.')
611 # process sign. The isinstance test rejects floats
612 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
613 raise ValueError("Invalid sign. The first value in the tuple "
614 "should be an integer; either 0 for a "
615 "positive number or 1 for a negative number.")
616 self._sign = value[0]
617 if value[2] == 'F':
618 # infinity: value[1] is ignored
619 self._int = '0'
620 self._exp = value[2]
621 self._is_special = True
622 else:
623 # process and validate the digits in value[1]
624 digits = []
625 for digit in value[1]:
626 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
627 # skip leading zeros
628 if digits or digit != 0:
629 digits.append(digit)
630 else:
631 raise ValueError("The second value in the tuple must "
632 "be composed of integers in the range "
633 "0 through 9.")
634 if value[2] in ('n', 'N'):
635 # NaN: digits form the diagnostic
636 self._int = ''.join(map(str, digits))
637 self._exp = value[2]
638 self._is_special = True
639 elif isinstance(value[2], (int, long)):
640 # finite number: digits give the coefficient
641 self._int = ''.join(map(str, digits or [0]))
642 self._exp = value[2]
643 self._is_special = False
644 else:
645 raise ValueError("The third value in the tuple must "
646 "be an integer, or one of the "
647 "strings 'F', 'n', 'N'.")
648 return self
650 if isinstance(value, float):
651 raise TypeError("Cannot convert float to Decimal. " +
652 "First convert the float to a string")
654 raise TypeError("Cannot convert %r to Decimal" % value)
656 def _isnan(self):
657 """Returns whether the number is not actually one.
659 0 if a number
660 1 if NaN
661 2 if sNaN
663 if self._is_special:
664 exp = self._exp
665 if exp == 'n':
666 return 1
667 elif exp == 'N':
668 return 2
669 return 0
671 def _isinfinity(self):
672 """Returns whether the number is infinite
674 0 if finite or not a number
675 1 if +INF
676 -1 if -INF
678 if self._exp == 'F':
679 if self._sign:
680 return -1
681 return 1
682 return 0
684 def _check_nans(self, other=None, context=None):
685 """Returns whether the number is not actually one.
687 if self, other are sNaN, signal
688 if self, other are NaN return nan
689 return 0
691 Done before operations.
694 self_is_nan = self._isnan()
695 if other is None:
696 other_is_nan = False
697 else:
698 other_is_nan = other._isnan()
700 if self_is_nan or other_is_nan:
701 if context is None:
702 context = getcontext()
704 if self_is_nan == 2:
705 return context._raise_error(InvalidOperation, 'sNaN',
706 self)
707 if other_is_nan == 2:
708 return context._raise_error(InvalidOperation, 'sNaN',
709 other)
710 if self_is_nan:
711 return self._fix_nan(context)
713 return other._fix_nan(context)
714 return 0
716 def _compare_check_nans(self, other, context):
717 """Version of _check_nans used for the signaling comparisons
718 compare_signal, __le__, __lt__, __ge__, __gt__.
720 Signal InvalidOperation if either self or other is a (quiet
721 or signaling) NaN. Signaling NaNs take precedence over quiet
722 NaNs.
724 Return 0 if neither operand is a NaN.
727 if context is None:
728 context = getcontext()
730 if self._is_special or other._is_special:
731 if self.is_snan():
732 return context._raise_error(InvalidOperation,
733 'comparison involving sNaN',
734 self)
735 elif other.is_snan():
736 return context._raise_error(InvalidOperation,
737 'comparison involving sNaN',
738 other)
739 elif self.is_qnan():
740 return context._raise_error(InvalidOperation,
741 'comparison involving NaN',
742 self)
743 elif other.is_qnan():
744 return context._raise_error(InvalidOperation,
745 'comparison involving NaN',
746 other)
747 return 0
749 def __nonzero__(self):
750 """Return True if self is nonzero; otherwise return False.
752 NaNs and infinities are considered nonzero.
754 return self._is_special or self._int != '0'
756 def _cmp(self, other):
757 """Compare the two non-NaN decimal instances self and other.
759 Returns -1 if self < other, 0 if self == other and 1
760 if self > other. This routine is for internal use only."""
762 if self._is_special or other._is_special:
763 return cmp(self._isinfinity(), other._isinfinity())
765 # check for zeros; note that cmp(0, -0) should return 0
766 if not self:
767 if not other:
768 return 0
769 else:
770 return -((-1)**other._sign)
771 if not other:
772 return (-1)**self._sign
774 # If different signs, neg one is less
775 if other._sign < self._sign:
776 return -1
777 if self._sign < other._sign:
778 return 1
780 self_adjusted = self.adjusted()
781 other_adjusted = other.adjusted()
782 if self_adjusted == other_adjusted:
783 self_padded = self._int + '0'*(self._exp - other._exp)
784 other_padded = other._int + '0'*(other._exp - self._exp)
785 return cmp(self_padded, other_padded) * (-1)**self._sign
786 elif self_adjusted > other_adjusted:
787 return (-1)**self._sign
788 else: # self_adjusted < other_adjusted
789 return -((-1)**self._sign)
791 # Note: The Decimal standard doesn't cover rich comparisons for
792 # Decimals. In particular, the specification is silent on the
793 # subject of what should happen for a comparison involving a NaN.
794 # We take the following approach:
796 # == comparisons involving a NaN always return False
797 # != comparisons involving a NaN always return True
798 # <, >, <= and >= comparisons involving a (quiet or signaling)
799 # NaN signal InvalidOperation, and return False if the
800 # InvalidOperation is not trapped.
802 # This behavior is designed to conform as closely as possible to
803 # that specified by IEEE 754.
805 def __eq__(self, other):
806 other = _convert_other(other)
807 if other is NotImplemented:
808 return other
809 if self.is_nan() or other.is_nan():
810 return False
811 return self._cmp(other) == 0
813 def __ne__(self, other):
814 other = _convert_other(other)
815 if other is NotImplemented:
816 return other
817 if self.is_nan() or other.is_nan():
818 return True
819 return self._cmp(other) != 0
821 def __lt__(self, other, context=None):
822 other = _convert_other(other)
823 if other is NotImplemented:
824 return other
825 ans = self._compare_check_nans(other, context)
826 if ans:
827 return False
828 return self._cmp(other) < 0
830 def __le__(self, other, context=None):
831 other = _convert_other(other)
832 if other is NotImplemented:
833 return other
834 ans = self._compare_check_nans(other, context)
835 if ans:
836 return False
837 return self._cmp(other) <= 0
839 def __gt__(self, other, context=None):
840 other = _convert_other(other)
841 if other is NotImplemented:
842 return other
843 ans = self._compare_check_nans(other, context)
844 if ans:
845 return False
846 return self._cmp(other) > 0
848 def __ge__(self, other, context=None):
849 other = _convert_other(other)
850 if other is NotImplemented:
851 return other
852 ans = self._compare_check_nans(other, context)
853 if ans:
854 return False
855 return self._cmp(other) >= 0
857 def compare(self, other, context=None):
858 """Compares one to another.
860 -1 => a < b
861 0 => a = b
862 1 => a > b
863 NaN => one is NaN
864 Like __cmp__, but returns Decimal instances.
866 other = _convert_other(other, raiseit=True)
868 # Compare(NaN, NaN) = NaN
869 if (self._is_special or other and other._is_special):
870 ans = self._check_nans(other, context)
871 if ans:
872 return ans
874 return Decimal(self._cmp(other))
876 def __hash__(self):
877 """x.__hash__() <==> hash(x)"""
878 # Decimal integers must hash the same as the ints
880 # The hash of a nonspecial noninteger Decimal must depend only
881 # on the value of that Decimal, and not on its representation.
882 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
883 if self._is_special:
884 if self._isnan():
885 raise TypeError('Cannot hash a NaN value.')
886 return hash(str(self))
887 if not self:
888 return 0
889 if self._isinteger():
890 op = _WorkRep(self.to_integral_value())
891 # to make computation feasible for Decimals with large
892 # exponent, we use the fact that hash(n) == hash(m) for
893 # any two nonzero integers n and m such that (i) n and m
894 # have the same sign, and (ii) n is congruent to m modulo
895 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
896 # hash((-1)**s*c*pow(10, e, 2**64-1).
897 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
898 # The value of a nonzero nonspecial Decimal instance is
899 # faithfully represented by the triple consisting of its sign,
900 # its adjusted exponent, and its coefficient with trailing
901 # zeros removed.
902 return hash((self._sign,
903 self._exp+len(self._int),
904 self._int.rstrip('0')))
906 def as_tuple(self):
907 """Represents the number as a triple tuple.
909 To show the internals exactly as they are.
911 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
913 def __repr__(self):
914 """Represents the number as an instance of Decimal."""
915 # Invariant: eval(repr(d)) == d
916 return "Decimal('%s')" % str(self)
918 def __str__(self, eng=False, context=None):
919 """Return string representation of the number in scientific notation.
921 Captures all of the information in the underlying representation.
924 sign = ['', '-'][self._sign]
925 if self._is_special:
926 if self._exp == 'F':
927 return sign + 'Infinity'
928 elif self._exp == 'n':
929 return sign + 'NaN' + self._int
930 else: # self._exp == 'N'
931 return sign + 'sNaN' + self._int
933 # number of digits of self._int to left of decimal point
934 leftdigits = self._exp + len(self._int)
936 # dotplace is number of digits of self._int to the left of the
937 # decimal point in the mantissa of the output string (that is,
938 # after adjusting the exponent)
939 if self._exp <= 0 and leftdigits > -6:
940 # no exponent required
941 dotplace = leftdigits
942 elif not eng:
943 # usual scientific notation: 1 digit on left of the point
944 dotplace = 1
945 elif self._int == '0':
946 # engineering notation, zero
947 dotplace = (leftdigits + 1) % 3 - 1
948 else:
949 # engineering notation, nonzero
950 dotplace = (leftdigits - 1) % 3 + 1
952 if dotplace <= 0:
953 intpart = '0'
954 fracpart = '.' + '0'*(-dotplace) + self._int
955 elif dotplace >= len(self._int):
956 intpart = self._int+'0'*(dotplace-len(self._int))
957 fracpart = ''
958 else:
959 intpart = self._int[:dotplace]
960 fracpart = '.' + self._int[dotplace:]
961 if leftdigits == dotplace:
962 exp = ''
963 else:
964 if context is None:
965 context = getcontext()
966 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
968 return sign + intpart + fracpart + exp
970 def to_eng_string(self, context=None):
971 """Convert to engineering-type string.
973 Engineering notation has an exponent which is a multiple of 3, so there
974 are up to 3 digits left of the decimal place.
976 Same rules for when in exponential and when as a value as in __str__.
978 return self.__str__(eng=True, context=context)
980 def __neg__(self, context=None):
981 """Returns a copy with the sign switched.
983 Rounds, if it has reason.
985 if self._is_special:
986 ans = self._check_nans(context=context)
987 if ans:
988 return ans
990 if not self:
991 # -Decimal('0') is Decimal('0'), not Decimal('-0')
992 ans = self.copy_abs()
993 else:
994 ans = self.copy_negate()
996 if context is None:
997 context = getcontext()
998 return ans._fix(context)
1000 def __pos__(self, context=None):
1001 """Returns a copy, unless it is a sNaN.
1003 Rounds the number (if more then precision digits)
1005 if self._is_special:
1006 ans = self._check_nans(context=context)
1007 if ans:
1008 return ans
1010 if not self:
1011 # + (-0) = 0
1012 ans = self.copy_abs()
1013 else:
1014 ans = Decimal(self)
1016 if context is None:
1017 context = getcontext()
1018 return ans._fix(context)
1020 def __abs__(self, round=True, context=None):
1021 """Returns the absolute value of self.
1023 If the keyword argument 'round' is false, do not round. The
1024 expression self.__abs__(round=False) is equivalent to
1025 self.copy_abs().
1027 if not round:
1028 return self.copy_abs()
1030 if self._is_special:
1031 ans = self._check_nans(context=context)
1032 if ans:
1033 return ans
1035 if self._sign:
1036 ans = self.__neg__(context=context)
1037 else:
1038 ans = self.__pos__(context=context)
1040 return ans
1042 def __add__(self, other, context=None):
1043 """Returns self + other.
1045 -INF + INF (or the reverse) cause InvalidOperation errors.
1047 other = _convert_other(other)
1048 if other is NotImplemented:
1049 return other
1051 if context is None:
1052 context = getcontext()
1054 if self._is_special or other._is_special:
1055 ans = self._check_nans(other, context)
1056 if ans:
1057 return ans
1059 if self._isinfinity():
1060 # If both INF, same sign => same as both, opposite => error.
1061 if self._sign != other._sign and other._isinfinity():
1062 return context._raise_error(InvalidOperation, '-INF + INF')
1063 return Decimal(self)
1064 if other._isinfinity():
1065 return Decimal(other) # Can't both be infinity here
1067 exp = min(self._exp, other._exp)
1068 negativezero = 0
1069 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1070 # If the answer is 0, the sign should be negative, in this case.
1071 negativezero = 1
1073 if not self and not other:
1074 sign = min(self._sign, other._sign)
1075 if negativezero:
1076 sign = 1
1077 ans = _dec_from_triple(sign, '0', exp)
1078 ans = ans._fix(context)
1079 return ans
1080 if not self:
1081 exp = max(exp, other._exp - context.prec-1)
1082 ans = other._rescale(exp, context.rounding)
1083 ans = ans._fix(context)
1084 return ans
1085 if not other:
1086 exp = max(exp, self._exp - context.prec-1)
1087 ans = self._rescale(exp, context.rounding)
1088 ans = ans._fix(context)
1089 return ans
1091 op1 = _WorkRep(self)
1092 op2 = _WorkRep(other)
1093 op1, op2 = _normalize(op1, op2, context.prec)
1095 result = _WorkRep()
1096 if op1.sign != op2.sign:
1097 # Equal and opposite
1098 if op1.int == op2.int:
1099 ans = _dec_from_triple(negativezero, '0', exp)
1100 ans = ans._fix(context)
1101 return ans
1102 if op1.int < op2.int:
1103 op1, op2 = op2, op1
1104 # OK, now abs(op1) > abs(op2)
1105 if op1.sign == 1:
1106 result.sign = 1
1107 op1.sign, op2.sign = op2.sign, op1.sign
1108 else:
1109 result.sign = 0
1110 # So we know the sign, and op1 > 0.
1111 elif op1.sign == 1:
1112 result.sign = 1
1113 op1.sign, op2.sign = (0, 0)
1114 else:
1115 result.sign = 0
1116 # Now, op1 > abs(op2) > 0
1118 if op2.sign == 0:
1119 result.int = op1.int + op2.int
1120 else:
1121 result.int = op1.int - op2.int
1123 result.exp = op1.exp
1124 ans = Decimal(result)
1125 ans = ans._fix(context)
1126 return ans
1128 __radd__ = __add__
1130 def __sub__(self, other, context=None):
1131 """Return self - other"""
1132 other = _convert_other(other)
1133 if other is NotImplemented:
1134 return other
1136 if self._is_special or other._is_special:
1137 ans = self._check_nans(other, context=context)
1138 if ans:
1139 return ans
1141 # self - other is computed as self + other.copy_negate()
1142 return self.__add__(other.copy_negate(), context=context)
1144 def __rsub__(self, other, context=None):
1145 """Return other - self"""
1146 other = _convert_other(other)
1147 if other is NotImplemented:
1148 return other
1150 return other.__sub__(self, context=context)
1152 def __mul__(self, other, context=None):
1153 """Return self * other.
1155 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1157 other = _convert_other(other)
1158 if other is NotImplemented:
1159 return other
1161 if context is None:
1162 context = getcontext()
1164 resultsign = self._sign ^ other._sign
1166 if self._is_special or other._is_special:
1167 ans = self._check_nans(other, context)
1168 if ans:
1169 return ans
1171 if self._isinfinity():
1172 if not other:
1173 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1174 return Infsign[resultsign]
1176 if other._isinfinity():
1177 if not self:
1178 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1179 return Infsign[resultsign]
1181 resultexp = self._exp + other._exp
1183 # Special case for multiplying by zero
1184 if not self or not other:
1185 ans = _dec_from_triple(resultsign, '0', resultexp)
1186 # Fixing in case the exponent is out of bounds
1187 ans = ans._fix(context)
1188 return ans
1190 # Special case for multiplying by power of 10
1191 if self._int == '1':
1192 ans = _dec_from_triple(resultsign, other._int, resultexp)
1193 ans = ans._fix(context)
1194 return ans
1195 if other._int == '1':
1196 ans = _dec_from_triple(resultsign, self._int, resultexp)
1197 ans = ans._fix(context)
1198 return ans
1200 op1 = _WorkRep(self)
1201 op2 = _WorkRep(other)
1203 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1204 ans = ans._fix(context)
1206 return ans
1207 __rmul__ = __mul__
1209 def __truediv__(self, other, context=None):
1210 """Return self / other."""
1211 other = _convert_other(other)
1212 if other is NotImplemented:
1213 return NotImplemented
1215 if context is None:
1216 context = getcontext()
1218 sign = self._sign ^ other._sign
1220 if self._is_special or other._is_special:
1221 ans = self._check_nans(other, context)
1222 if ans:
1223 return ans
1225 if self._isinfinity() and other._isinfinity():
1226 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1228 if self._isinfinity():
1229 return Infsign[sign]
1231 if other._isinfinity():
1232 context._raise_error(Clamped, 'Division by infinity')
1233 return _dec_from_triple(sign, '0', context.Etiny())
1235 # Special cases for zeroes
1236 if not other:
1237 if not self:
1238 return context._raise_error(DivisionUndefined, '0 / 0')
1239 return context._raise_error(DivisionByZero, 'x / 0', sign)
1241 if not self:
1242 exp = self._exp - other._exp
1243 coeff = 0
1244 else:
1245 # OK, so neither = 0, INF or NaN
1246 shift = len(other._int) - len(self._int) + context.prec + 1
1247 exp = self._exp - other._exp - shift
1248 op1 = _WorkRep(self)
1249 op2 = _WorkRep(other)
1250 if shift >= 0:
1251 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1252 else:
1253 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1254 if remainder:
1255 # result is not exact; adjust to ensure correct rounding
1256 if coeff % 5 == 0:
1257 coeff += 1
1258 else:
1259 # result is exact; get as close to ideal exponent as possible
1260 ideal_exp = self._exp - other._exp
1261 while exp < ideal_exp and coeff % 10 == 0:
1262 coeff //= 10
1263 exp += 1
1265 ans = _dec_from_triple(sign, str(coeff), exp)
1266 return ans._fix(context)
1268 def _divide(self, other, context):
1269 """Return (self // other, self % other), to context.prec precision.
1271 Assumes that neither self nor other is a NaN, that self is not
1272 infinite and that other is nonzero.
1274 sign = self._sign ^ other._sign
1275 if other._isinfinity():
1276 ideal_exp = self._exp
1277 else:
1278 ideal_exp = min(self._exp, other._exp)
1280 expdiff = self.adjusted() - other.adjusted()
1281 if not self or other._isinfinity() or expdiff <= -2:
1282 return (_dec_from_triple(sign, '0', 0),
1283 self._rescale(ideal_exp, context.rounding))
1284 if expdiff <= context.prec:
1285 op1 = _WorkRep(self)
1286 op2 = _WorkRep(other)
1287 if op1.exp >= op2.exp:
1288 op1.int *= 10**(op1.exp - op2.exp)
1289 else:
1290 op2.int *= 10**(op2.exp - op1.exp)
1291 q, r = divmod(op1.int, op2.int)
1292 if q < 10**context.prec:
1293 return (_dec_from_triple(sign, str(q), 0),
1294 _dec_from_triple(self._sign, str(r), ideal_exp))
1296 # Here the quotient is too large to be representable
1297 ans = context._raise_error(DivisionImpossible,
1298 'quotient too large in //, % or divmod')
1299 return ans, ans
1301 def __rtruediv__(self, other, context=None):
1302 """Swaps self/other and returns __truediv__."""
1303 other = _convert_other(other)
1304 if other is NotImplemented:
1305 return other
1306 return other.__truediv__(self, context=context)
1308 __div__ = __truediv__
1309 __rdiv__ = __rtruediv__
1311 def __divmod__(self, other, context=None):
1313 Return (self // other, self % other)
1315 other = _convert_other(other)
1316 if other is NotImplemented:
1317 return other
1319 if context is None:
1320 context = getcontext()
1322 ans = self._check_nans(other, context)
1323 if ans:
1324 return (ans, ans)
1326 sign = self._sign ^ other._sign
1327 if self._isinfinity():
1328 if other._isinfinity():
1329 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1330 return ans, ans
1331 else:
1332 return (Infsign[sign],
1333 context._raise_error(InvalidOperation, 'INF % x'))
1335 if not other:
1336 if not self:
1337 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1338 return ans, ans
1339 else:
1340 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1341 context._raise_error(InvalidOperation, 'x % 0'))
1343 quotient, remainder = self._divide(other, context)
1344 remainder = remainder._fix(context)
1345 return quotient, remainder
1347 def __rdivmod__(self, other, context=None):
1348 """Swaps self/other and returns __divmod__."""
1349 other = _convert_other(other)
1350 if other is NotImplemented:
1351 return other
1352 return other.__divmod__(self, context=context)
1354 def __mod__(self, other, context=None):
1356 self % other
1358 other = _convert_other(other)
1359 if other is NotImplemented:
1360 return other
1362 if context is None:
1363 context = getcontext()
1365 ans = self._check_nans(other, context)
1366 if ans:
1367 return ans
1369 if self._isinfinity():
1370 return context._raise_error(InvalidOperation, 'INF % x')
1371 elif not other:
1372 if self:
1373 return context._raise_error(InvalidOperation, 'x % 0')
1374 else:
1375 return context._raise_error(DivisionUndefined, '0 % 0')
1377 remainder = self._divide(other, context)[1]
1378 remainder = remainder._fix(context)
1379 return remainder
1381 def __rmod__(self, other, context=None):
1382 """Swaps self/other and returns __mod__."""
1383 other = _convert_other(other)
1384 if other is NotImplemented:
1385 return other
1386 return other.__mod__(self, context=context)
1388 def remainder_near(self, other, context=None):
1390 Remainder nearest to 0- abs(remainder-near) <= other/2
1392 if context is None:
1393 context = getcontext()
1395 other = _convert_other(other, raiseit=True)
1397 ans = self._check_nans(other, context)
1398 if ans:
1399 return ans
1401 # self == +/-infinity -> InvalidOperation
1402 if self._isinfinity():
1403 return context._raise_error(InvalidOperation,
1404 'remainder_near(infinity, x)')
1406 # other == 0 -> either InvalidOperation or DivisionUndefined
1407 if not other:
1408 if self:
1409 return context._raise_error(InvalidOperation,
1410 'remainder_near(x, 0)')
1411 else:
1412 return context._raise_error(DivisionUndefined,
1413 'remainder_near(0, 0)')
1415 # other = +/-infinity -> remainder = self
1416 if other._isinfinity():
1417 ans = Decimal(self)
1418 return ans._fix(context)
1420 # self = 0 -> remainder = self, with ideal exponent
1421 ideal_exponent = min(self._exp, other._exp)
1422 if not self:
1423 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1424 return ans._fix(context)
1426 # catch most cases of large or small quotient
1427 expdiff = self.adjusted() - other.adjusted()
1428 if expdiff >= context.prec + 1:
1429 # expdiff >= prec+1 => abs(self/other) > 10**prec
1430 return context._raise_error(DivisionImpossible)
1431 if expdiff <= -2:
1432 # expdiff <= -2 => abs(self/other) < 0.1
1433 ans = self._rescale(ideal_exponent, context.rounding)
1434 return ans._fix(context)
1436 # adjust both arguments to have the same exponent, then divide
1437 op1 = _WorkRep(self)
1438 op2 = _WorkRep(other)
1439 if op1.exp >= op2.exp:
1440 op1.int *= 10**(op1.exp - op2.exp)
1441 else:
1442 op2.int *= 10**(op2.exp - op1.exp)
1443 q, r = divmod(op1.int, op2.int)
1444 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1445 # 10**ideal_exponent. Apply correction to ensure that
1446 # abs(remainder) <= abs(other)/2
1447 if 2*r + (q&1) > op2.int:
1448 r -= op2.int
1449 q += 1
1451 if q >= 10**context.prec:
1452 return context._raise_error(DivisionImpossible)
1454 # result has same sign as self unless r is negative
1455 sign = self._sign
1456 if r < 0:
1457 sign = 1-sign
1458 r = -r
1460 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1461 return ans._fix(context)
1463 def __floordiv__(self, other, context=None):
1464 """self // other"""
1465 other = _convert_other(other)
1466 if other is NotImplemented:
1467 return other
1469 if context is None:
1470 context = getcontext()
1472 ans = self._check_nans(other, context)
1473 if ans:
1474 return ans
1476 if self._isinfinity():
1477 if other._isinfinity():
1478 return context._raise_error(InvalidOperation, 'INF // INF')
1479 else:
1480 return Infsign[self._sign ^ other._sign]
1482 if not other:
1483 if self:
1484 return context._raise_error(DivisionByZero, 'x // 0',
1485 self._sign ^ other._sign)
1486 else:
1487 return context._raise_error(DivisionUndefined, '0 // 0')
1489 return self._divide(other, context)[0]
1491 def __rfloordiv__(self, other, context=None):
1492 """Swaps self/other and returns __floordiv__."""
1493 other = _convert_other(other)
1494 if other is NotImplemented:
1495 return other
1496 return other.__floordiv__(self, context=context)
1498 def __float__(self):
1499 """Float representation."""
1500 return float(str(self))
1502 def __int__(self):
1503 """Converts self to an int, truncating if necessary."""
1504 if self._is_special:
1505 if self._isnan():
1506 context = getcontext()
1507 return context._raise_error(InvalidContext)
1508 elif self._isinfinity():
1509 raise OverflowError("Cannot convert infinity to int")
1510 s = (-1)**self._sign
1511 if self._exp >= 0:
1512 return s*int(self._int)*10**self._exp
1513 else:
1514 return s*int(self._int[:self._exp] or '0')
1516 __trunc__ = __int__
1518 @property
1519 def real(self):
1520 return self
1522 @property
1523 def imag(self):
1524 return Decimal(0)
1526 def conjugate(self):
1527 return self
1529 def __complex__(self):
1530 return complex(float(self))
1532 def __long__(self):
1533 """Converts to a long.
1535 Equivalent to long(int(self))
1537 return long(self.__int__())
1539 def _fix_nan(self, context):
1540 """Decapitate the payload of a NaN to fit the context"""
1541 payload = self._int
1543 # maximum length of payload is precision if _clamp=0,
1544 # precision-1 if _clamp=1.
1545 max_payload_len = context.prec - context._clamp
1546 if len(payload) > max_payload_len:
1547 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1548 return _dec_from_triple(self._sign, payload, self._exp, True)
1549 return Decimal(self)
1551 def _fix(self, context):
1552 """Round if it is necessary to keep self within prec precision.
1554 Rounds and fixes the exponent. Does not raise on a sNaN.
1556 Arguments:
1557 self - Decimal instance
1558 context - context used.
1561 if self._is_special:
1562 if self._isnan():
1563 # decapitate payload if necessary
1564 return self._fix_nan(context)
1565 else:
1566 # self is +/-Infinity; return unaltered
1567 return Decimal(self)
1569 # if self is zero then exponent should be between Etiny and
1570 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1571 Etiny = context.Etiny()
1572 Etop = context.Etop()
1573 if not self:
1574 exp_max = [context.Emax, Etop][context._clamp]
1575 new_exp = min(max(self._exp, Etiny), exp_max)
1576 if new_exp != self._exp:
1577 context._raise_error(Clamped)
1578 return _dec_from_triple(self._sign, '0', new_exp)
1579 else:
1580 return Decimal(self)
1582 # exp_min is the smallest allowable exponent of the result,
1583 # equal to max(self.adjusted()-context.prec+1, Etiny)
1584 exp_min = len(self._int) + self._exp - context.prec
1585 if exp_min > Etop:
1586 # overflow: exp_min > Etop iff self.adjusted() > Emax
1587 context._raise_error(Inexact)
1588 context._raise_error(Rounded)
1589 return context._raise_error(Overflow, 'above Emax', self._sign)
1590 self_is_subnormal = exp_min < Etiny
1591 if self_is_subnormal:
1592 context._raise_error(Subnormal)
1593 exp_min = Etiny
1595 # round if self has too many digits
1596 if self._exp < exp_min:
1597 context._raise_error(Rounded)
1598 digits = len(self._int) + self._exp - exp_min
1599 if digits < 0:
1600 self = _dec_from_triple(self._sign, '1', exp_min-1)
1601 digits = 0
1602 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1603 changed = this_function(digits)
1604 coeff = self._int[:digits] or '0'
1605 if changed == 1:
1606 coeff = str(int(coeff)+1)
1607 ans = _dec_from_triple(self._sign, coeff, exp_min)
1609 if changed:
1610 context._raise_error(Inexact)
1611 if self_is_subnormal:
1612 context._raise_error(Underflow)
1613 if not ans:
1614 # raise Clamped on underflow to 0
1615 context._raise_error(Clamped)
1616 elif len(ans._int) == context.prec+1:
1617 # we get here only if rescaling rounds the
1618 # cofficient up to exactly 10**context.prec
1619 if ans._exp < Etop:
1620 ans = _dec_from_triple(ans._sign,
1621 ans._int[:-1], ans._exp+1)
1622 else:
1623 # Inexact and Rounded have already been raised
1624 ans = context._raise_error(Overflow, 'above Emax',
1625 self._sign)
1626 return ans
1628 # fold down if _clamp == 1 and self has too few digits
1629 if context._clamp == 1 and self._exp > Etop:
1630 context._raise_error(Clamped)
1631 self_padded = self._int + '0'*(self._exp - Etop)
1632 return _dec_from_triple(self._sign, self_padded, Etop)
1634 # here self was representable to begin with; return unchanged
1635 return Decimal(self)
1637 _pick_rounding_function = {}
1639 # for each of the rounding functions below:
1640 # self is a finite, nonzero Decimal
1641 # prec is an integer satisfying 0 <= prec < len(self._int)
1643 # each function returns either -1, 0, or 1, as follows:
1644 # 1 indicates that self should be rounded up (away from zero)
1645 # 0 indicates that self should be truncated, and that all the
1646 # digits to be truncated are zeros (so the value is unchanged)
1647 # -1 indicates that there are nonzero digits to be truncated
1649 def _round_down(self, prec):
1650 """Also known as round-towards-0, truncate."""
1651 if _all_zeros(self._int, prec):
1652 return 0
1653 else:
1654 return -1
1656 def _round_up(self, prec):
1657 """Rounds away from 0."""
1658 return -self._round_down(prec)
1660 def _round_half_up(self, prec):
1661 """Rounds 5 up (away from 0)"""
1662 if self._int[prec] in '56789':
1663 return 1
1664 elif _all_zeros(self._int, prec):
1665 return 0
1666 else:
1667 return -1
1669 def _round_half_down(self, prec):
1670 """Round 5 down"""
1671 if _exact_half(self._int, prec):
1672 return -1
1673 else:
1674 return self._round_half_up(prec)
1676 def _round_half_even(self, prec):
1677 """Round 5 to even, rest to nearest."""
1678 if _exact_half(self._int, prec) and \
1679 (prec == 0 or self._int[prec-1] in '02468'):
1680 return -1
1681 else:
1682 return self._round_half_up(prec)
1684 def _round_ceiling(self, prec):
1685 """Rounds up (not away from 0 if negative.)"""
1686 if self._sign:
1687 return self._round_down(prec)
1688 else:
1689 return -self._round_down(prec)
1691 def _round_floor(self, prec):
1692 """Rounds down (not towards 0 if negative)"""
1693 if not self._sign:
1694 return self._round_down(prec)
1695 else:
1696 return -self._round_down(prec)
1698 def _round_05up(self, prec):
1699 """Round down unless digit prec-1 is 0 or 5."""
1700 if prec and self._int[prec-1] not in '05':
1701 return self._round_down(prec)
1702 else:
1703 return -self._round_down(prec)
1705 def fma(self, other, third, context=None):
1706 """Fused multiply-add.
1708 Returns self*other+third with no rounding of the intermediate
1709 product self*other.
1711 self and other are multiplied together, with no rounding of
1712 the result. The third operand is then added to the result,
1713 and a single final rounding is performed.
1716 other = _convert_other(other, raiseit=True)
1718 # compute product; raise InvalidOperation if either operand is
1719 # a signaling NaN or if the product is zero times infinity.
1720 if self._is_special or other._is_special:
1721 if context is None:
1722 context = getcontext()
1723 if self._exp == 'N':
1724 return context._raise_error(InvalidOperation, 'sNaN', self)
1725 if other._exp == 'N':
1726 return context._raise_error(InvalidOperation, 'sNaN', other)
1727 if self._exp == 'n':
1728 product = self
1729 elif other._exp == 'n':
1730 product = other
1731 elif self._exp == 'F':
1732 if not other:
1733 return context._raise_error(InvalidOperation,
1734 'INF * 0 in fma')
1735 product = Infsign[self._sign ^ other._sign]
1736 elif other._exp == 'F':
1737 if not self:
1738 return context._raise_error(InvalidOperation,
1739 '0 * INF in fma')
1740 product = Infsign[self._sign ^ other._sign]
1741 else:
1742 product = _dec_from_triple(self._sign ^ other._sign,
1743 str(int(self._int) * int(other._int)),
1744 self._exp + other._exp)
1746 third = _convert_other(third, raiseit=True)
1747 return product.__add__(third, context)
1749 def _power_modulo(self, other, modulo, context=None):
1750 """Three argument version of __pow__"""
1752 # if can't convert other and modulo to Decimal, raise
1753 # TypeError; there's no point returning NotImplemented (no
1754 # equivalent of __rpow__ for three argument pow)
1755 other = _convert_other(other, raiseit=True)
1756 modulo = _convert_other(modulo, raiseit=True)
1758 if context is None:
1759 context = getcontext()
1761 # deal with NaNs: if there are any sNaNs then first one wins,
1762 # (i.e. behaviour for NaNs is identical to that of fma)
1763 self_is_nan = self._isnan()
1764 other_is_nan = other._isnan()
1765 modulo_is_nan = modulo._isnan()
1766 if self_is_nan or other_is_nan or modulo_is_nan:
1767 if self_is_nan == 2:
1768 return context._raise_error(InvalidOperation, 'sNaN',
1769 self)
1770 if other_is_nan == 2:
1771 return context._raise_error(InvalidOperation, 'sNaN',
1772 other)
1773 if modulo_is_nan == 2:
1774 return context._raise_error(InvalidOperation, 'sNaN',
1775 modulo)
1776 if self_is_nan:
1777 return self._fix_nan(context)
1778 if other_is_nan:
1779 return other._fix_nan(context)
1780 return modulo._fix_nan(context)
1782 # check inputs: we apply same restrictions as Python's pow()
1783 if not (self._isinteger() and
1784 other._isinteger() and
1785 modulo._isinteger()):
1786 return context._raise_error(InvalidOperation,
1787 'pow() 3rd argument not allowed '
1788 'unless all arguments are integers')
1789 if other < 0:
1790 return context._raise_error(InvalidOperation,
1791 'pow() 2nd argument cannot be '
1792 'negative when 3rd argument specified')
1793 if not modulo:
1794 return context._raise_error(InvalidOperation,
1795 'pow() 3rd argument cannot be 0')
1797 # additional restriction for decimal: the modulus must be less
1798 # than 10**prec in absolute value
1799 if modulo.adjusted() >= context.prec:
1800 return context._raise_error(InvalidOperation,
1801 'insufficient precision: pow() 3rd '
1802 'argument must not have more than '
1803 'precision digits')
1805 # define 0**0 == NaN, for consistency with two-argument pow
1806 # (even though it hurts!)
1807 if not other and not self:
1808 return context._raise_error(InvalidOperation,
1809 'at least one of pow() 1st argument '
1810 'and 2nd argument must be nonzero ;'
1811 '0**0 is not defined')
1813 # compute sign of result
1814 if other._iseven():
1815 sign = 0
1816 else:
1817 sign = self._sign
1819 # convert modulo to a Python integer, and self and other to
1820 # Decimal integers (i.e. force their exponents to be >= 0)
1821 modulo = abs(int(modulo))
1822 base = _WorkRep(self.to_integral_value())
1823 exponent = _WorkRep(other.to_integral_value())
1825 # compute result using integer pow()
1826 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1827 for i in xrange(exponent.exp):
1828 base = pow(base, 10, modulo)
1829 base = pow(base, exponent.int, modulo)
1831 return _dec_from_triple(sign, str(base), 0)
1833 def _power_exact(self, other, p):
1834 """Attempt to compute self**other exactly.
1836 Given Decimals self and other and an integer p, attempt to
1837 compute an exact result for the power self**other, with p
1838 digits of precision. Return None if self**other is not
1839 exactly representable in p digits.
1841 Assumes that elimination of special cases has already been
1842 performed: self and other must both be nonspecial; self must
1843 be positive and not numerically equal to 1; other must be
1844 nonzero. For efficiency, other._exp should not be too large,
1845 so that 10**abs(other._exp) is a feasible calculation."""
1847 # In the comments below, we write x for the value of self and
1848 # y for the value of other. Write x = xc*10**xe and y =
1849 # yc*10**ye.
1851 # The main purpose of this method is to identify the *failure*
1852 # of x**y to be exactly representable with as little effort as
1853 # possible. So we look for cheap and easy tests that
1854 # eliminate the possibility of x**y being exact. Only if all
1855 # these tests are passed do we go on to actually compute x**y.
1857 # Here's the main idea. First normalize both x and y. We
1858 # express y as a rational m/n, with m and n relatively prime
1859 # and n>0. Then for x**y to be exactly representable (at
1860 # *any* precision), xc must be the nth power of a positive
1861 # integer and xe must be divisible by n. If m is negative
1862 # then additionally xc must be a power of either 2 or 5, hence
1863 # a power of 2**n or 5**n.
1865 # There's a limit to how small |y| can be: if y=m/n as above
1866 # then:
1868 # (1) if xc != 1 then for the result to be representable we
1869 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1870 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1871 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1872 # representable.
1874 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1875 # |y| < 1/|xe| then the result is not representable.
1877 # Note that since x is not equal to 1, at least one of (1) and
1878 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1879 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1881 # There's also a limit to how large y can be, at least if it's
1882 # positive: the normalized result will have coefficient xc**y,
1883 # so if it's representable then xc**y < 10**p, and y <
1884 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1885 # not exactly representable.
1887 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1888 # so |y| < 1/xe and the result is not representable.
1889 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1890 # < 1/nbits(xc).
1892 x = _WorkRep(self)
1893 xc, xe = x.int, x.exp
1894 while xc % 10 == 0:
1895 xc //= 10
1896 xe += 1
1898 y = _WorkRep(other)
1899 yc, ye = y.int, y.exp
1900 while yc % 10 == 0:
1901 yc //= 10
1902 ye += 1
1904 # case where xc == 1: result is 10**(xe*y), with xe*y
1905 # required to be an integer
1906 if xc == 1:
1907 if ye >= 0:
1908 exponent = xe*yc*10**ye
1909 else:
1910 exponent, remainder = divmod(xe*yc, 10**-ye)
1911 if remainder:
1912 return None
1913 if y.sign == 1:
1914 exponent = -exponent
1915 # if other is a nonnegative integer, use ideal exponent
1916 if other._isinteger() and other._sign == 0:
1917 ideal_exponent = self._exp*int(other)
1918 zeros = min(exponent-ideal_exponent, p-1)
1919 else:
1920 zeros = 0
1921 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1923 # case where y is negative: xc must be either a power
1924 # of 2 or a power of 5.
1925 if y.sign == 1:
1926 last_digit = xc % 10
1927 if last_digit in (2,4,6,8):
1928 # quick test for power of 2
1929 if xc & -xc != xc:
1930 return None
1931 # now xc is a power of 2; e is its exponent
1932 e = _nbits(xc)-1
1933 # find e*y and xe*y; both must be integers
1934 if ye >= 0:
1935 y_as_int = yc*10**ye
1936 e = e*y_as_int
1937 xe = xe*y_as_int
1938 else:
1939 ten_pow = 10**-ye
1940 e, remainder = divmod(e*yc, ten_pow)
1941 if remainder:
1942 return None
1943 xe, remainder = divmod(xe*yc, ten_pow)
1944 if remainder:
1945 return None
1947 if e*65 >= p*93: # 93/65 > log(10)/log(5)
1948 return None
1949 xc = 5**e
1951 elif last_digit == 5:
1952 # e >= log_5(xc) if xc is a power of 5; we have
1953 # equality all the way up to xc=5**2658
1954 e = _nbits(xc)*28//65
1955 xc, remainder = divmod(5**e, xc)
1956 if remainder:
1957 return None
1958 while xc % 5 == 0:
1959 xc //= 5
1960 e -= 1
1961 if ye >= 0:
1962 y_as_integer = yc*10**ye
1963 e = e*y_as_integer
1964 xe = xe*y_as_integer
1965 else:
1966 ten_pow = 10**-ye
1967 e, remainder = divmod(e*yc, ten_pow)
1968 if remainder:
1969 return None
1970 xe, remainder = divmod(xe*yc, ten_pow)
1971 if remainder:
1972 return None
1973 if e*3 >= p*10: # 10/3 > log(10)/log(2)
1974 return None
1975 xc = 2**e
1976 else:
1977 return None
1979 if xc >= 10**p:
1980 return None
1981 xe = -e-xe
1982 return _dec_from_triple(0, str(xc), xe)
1984 # now y is positive; find m and n such that y = m/n
1985 if ye >= 0:
1986 m, n = yc*10**ye, 1
1987 else:
1988 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
1989 return None
1990 xc_bits = _nbits(xc)
1991 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
1992 return None
1993 m, n = yc, 10**(-ye)
1994 while m % 2 == n % 2 == 0:
1995 m //= 2
1996 n //= 2
1997 while m % 5 == n % 5 == 0:
1998 m //= 5
1999 n //= 5
2001 # compute nth root of xc*10**xe
2002 if n > 1:
2003 # if 1 < xc < 2**n then xc isn't an nth power
2004 if xc != 1 and xc_bits <= n:
2005 return None
2007 xe, rem = divmod(xe, n)
2008 if rem != 0:
2009 return None
2011 # compute nth root of xc using Newton's method
2012 a = 1L << -(-_nbits(xc)//n) # initial estimate
2013 while True:
2014 q, r = divmod(xc, a**(n-1))
2015 if a <= q:
2016 break
2017 else:
2018 a = (a*(n-1) + q)//n
2019 if not (a == q and r == 0):
2020 return None
2021 xc = a
2023 # now xc*10**xe is the nth root of the original xc*10**xe
2024 # compute mth power of xc*10**xe
2026 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2027 # 10**p and the result is not representable.
2028 if xc > 1 and m > p*100//_log10_lb(xc):
2029 return None
2030 xc = xc**m
2031 xe *= m
2032 if xc > 10**p:
2033 return None
2035 # by this point the result *is* exactly representable
2036 # adjust the exponent to get as close as possible to the ideal
2037 # exponent, if necessary
2038 str_xc = str(xc)
2039 if other._isinteger() and other._sign == 0:
2040 ideal_exponent = self._exp*int(other)
2041 zeros = min(xe-ideal_exponent, p-len(str_xc))
2042 else:
2043 zeros = 0
2044 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2046 def __pow__(self, other, modulo=None, context=None):
2047 """Return self ** other [ % modulo].
2049 With two arguments, compute self**other.
2051 With three arguments, compute (self**other) % modulo. For the
2052 three argument form, the following restrictions on the
2053 arguments hold:
2055 - all three arguments must be integral
2056 - other must be nonnegative
2057 - either self or other (or both) must be nonzero
2058 - modulo must be nonzero and must have at most p digits,
2059 where p is the context precision.
2061 If any of these restrictions is violated the InvalidOperation
2062 flag is raised.
2064 The result of pow(self, other, modulo) is identical to the
2065 result that would be obtained by computing (self**other) %
2066 modulo with unbounded precision, but is computed more
2067 efficiently. It is always exact.
2070 if modulo is not None:
2071 return self._power_modulo(other, modulo, context)
2073 other = _convert_other(other)
2074 if other is NotImplemented:
2075 return other
2077 if context is None:
2078 context = getcontext()
2080 # either argument is a NaN => result is NaN
2081 ans = self._check_nans(other, context)
2082 if ans:
2083 return ans
2085 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2086 if not other:
2087 if not self:
2088 return context._raise_error(InvalidOperation, '0 ** 0')
2089 else:
2090 return Dec_p1
2092 # result has sign 1 iff self._sign is 1 and other is an odd integer
2093 result_sign = 0
2094 if self._sign == 1:
2095 if other._isinteger():
2096 if not other._iseven():
2097 result_sign = 1
2098 else:
2099 # -ve**noninteger = NaN
2100 # (-0)**noninteger = 0**noninteger
2101 if self:
2102 return context._raise_error(InvalidOperation,
2103 'x ** y with x negative and y not an integer')
2104 # negate self, without doing any unwanted rounding
2105 self = self.copy_negate()
2107 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2108 if not self:
2109 if other._sign == 0:
2110 return _dec_from_triple(result_sign, '0', 0)
2111 else:
2112 return Infsign[result_sign]
2114 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2115 if self._isinfinity():
2116 if other._sign == 0:
2117 return Infsign[result_sign]
2118 else:
2119 return _dec_from_triple(result_sign, '0', 0)
2121 # 1**other = 1, but the choice of exponent and the flags
2122 # depend on the exponent of self, and on whether other is a
2123 # positive integer, a negative integer, or neither
2124 if self == Dec_p1:
2125 if other._isinteger():
2126 # exp = max(self._exp*max(int(other), 0),
2127 # 1-context.prec) but evaluating int(other) directly
2128 # is dangerous until we know other is small (other
2129 # could be 1e999999999)
2130 if other._sign == 1:
2131 multiplier = 0
2132 elif other > context.prec:
2133 multiplier = context.prec
2134 else:
2135 multiplier = int(other)
2137 exp = self._exp * multiplier
2138 if exp < 1-context.prec:
2139 exp = 1-context.prec
2140 context._raise_error(Rounded)
2141 else:
2142 context._raise_error(Inexact)
2143 context._raise_error(Rounded)
2144 exp = 1-context.prec
2146 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2148 # compute adjusted exponent of self
2149 self_adj = self.adjusted()
2151 # self ** infinity is infinity if self > 1, 0 if self < 1
2152 # self ** -infinity is infinity if self < 1, 0 if self > 1
2153 if other._isinfinity():
2154 if (other._sign == 0) == (self_adj < 0):
2155 return _dec_from_triple(result_sign, '0', 0)
2156 else:
2157 return Infsign[result_sign]
2159 # from here on, the result always goes through the call
2160 # to _fix at the end of this function.
2161 ans = None
2163 # crude test to catch cases of extreme overflow/underflow. If
2164 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2165 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2166 # self**other >= 10**(Emax+1), so overflow occurs. The test
2167 # for underflow is similar.
2168 bound = self._log10_exp_bound() + other.adjusted()
2169 if (self_adj >= 0) == (other._sign == 0):
2170 # self > 1 and other +ve, or self < 1 and other -ve
2171 # possibility of overflow
2172 if bound >= len(str(context.Emax)):
2173 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2174 else:
2175 # self > 1 and other -ve, or self < 1 and other +ve
2176 # possibility of underflow to 0
2177 Etiny = context.Etiny()
2178 if bound >= len(str(-Etiny)):
2179 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2181 # try for an exact result with precision +1
2182 if ans is None:
2183 ans = self._power_exact(other, context.prec + 1)
2184 if ans is not None and result_sign == 1:
2185 ans = _dec_from_triple(1, ans._int, ans._exp)
2187 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2188 if ans is None:
2189 p = context.prec
2190 x = _WorkRep(self)
2191 xc, xe = x.int, x.exp
2192 y = _WorkRep(other)
2193 yc, ye = y.int, y.exp
2194 if y.sign == 1:
2195 yc = -yc
2197 # compute correctly rounded result: start with precision +3,
2198 # then increase precision until result is unambiguously roundable
2199 extra = 3
2200 while True:
2201 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2202 if coeff % (5*10**(len(str(coeff))-p-1)):
2203 break
2204 extra += 3
2206 ans = _dec_from_triple(result_sign, str(coeff), exp)
2208 # the specification says that for non-integer other we need to
2209 # raise Inexact, even when the result is actually exact. In
2210 # the same way, we need to raise Underflow here if the result
2211 # is subnormal. (The call to _fix will take care of raising
2212 # Rounded and Subnormal, as usual.)
2213 if not other._isinteger():
2214 context._raise_error(Inexact)
2215 # pad with zeros up to length context.prec+1 if necessary
2216 if len(ans._int) <= context.prec:
2217 expdiff = context.prec+1 - len(ans._int)
2218 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2219 ans._exp-expdiff)
2220 if ans.adjusted() < context.Emin:
2221 context._raise_error(Underflow)
2223 # unlike exp, ln and log10, the power function respects the
2224 # rounding mode; no need to use ROUND_HALF_EVEN here
2225 ans = ans._fix(context)
2226 return ans
2228 def __rpow__(self, other, context=None):
2229 """Swaps self/other and returns __pow__."""
2230 other = _convert_other(other)
2231 if other is NotImplemented:
2232 return other
2233 return other.__pow__(self, context=context)
2235 def normalize(self, context=None):
2236 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2238 if context is None:
2239 context = getcontext()
2241 if self._is_special:
2242 ans = self._check_nans(context=context)
2243 if ans:
2244 return ans
2246 dup = self._fix(context)
2247 if dup._isinfinity():
2248 return dup
2250 if not dup:
2251 return _dec_from_triple(dup._sign, '0', 0)
2252 exp_max = [context.Emax, context.Etop()][context._clamp]
2253 end = len(dup._int)
2254 exp = dup._exp
2255 while dup._int[end-1] == '0' and exp < exp_max:
2256 exp += 1
2257 end -= 1
2258 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2260 def quantize(self, exp, rounding=None, context=None, watchexp=True):
2261 """Quantize self so its exponent is the same as that of exp.
2263 Similar to self._rescale(exp._exp) but with error checking.
2265 exp = _convert_other(exp, raiseit=True)
2267 if context is None:
2268 context = getcontext()
2269 if rounding is None:
2270 rounding = context.rounding
2272 if self._is_special or exp._is_special:
2273 ans = self._check_nans(exp, context)
2274 if ans:
2275 return ans
2277 if exp._isinfinity() or self._isinfinity():
2278 if exp._isinfinity() and self._isinfinity():
2279 return Decimal(self) # if both are inf, it is OK
2280 return context._raise_error(InvalidOperation,
2281 'quantize with one INF')
2283 # if we're not watching exponents, do a simple rescale
2284 if not watchexp:
2285 ans = self._rescale(exp._exp, rounding)
2286 # raise Inexact and Rounded where appropriate
2287 if ans._exp > self._exp:
2288 context._raise_error(Rounded)
2289 if ans != self:
2290 context._raise_error(Inexact)
2291 return ans
2293 # exp._exp should be between Etiny and Emax
2294 if not (context.Etiny() <= exp._exp <= context.Emax):
2295 return context._raise_error(InvalidOperation,
2296 'target exponent out of bounds in quantize')
2298 if not self:
2299 ans = _dec_from_triple(self._sign, '0', exp._exp)
2300 return ans._fix(context)
2302 self_adjusted = self.adjusted()
2303 if self_adjusted > context.Emax:
2304 return context._raise_error(InvalidOperation,
2305 'exponent of quantize result too large for current context')
2306 if self_adjusted - exp._exp + 1 > context.prec:
2307 return context._raise_error(InvalidOperation,
2308 'quantize result has too many digits for current context')
2310 ans = self._rescale(exp._exp, rounding)
2311 if ans.adjusted() > context.Emax:
2312 return context._raise_error(InvalidOperation,
2313 'exponent of quantize result too large for current context')
2314 if len(ans._int) > context.prec:
2315 return context._raise_error(InvalidOperation,
2316 'quantize result has too many digits for current context')
2318 # raise appropriate flags
2319 if ans._exp > self._exp:
2320 context._raise_error(Rounded)
2321 if ans != self:
2322 context._raise_error(Inexact)
2323 if ans and ans.adjusted() < context.Emin:
2324 context._raise_error(Subnormal)
2326 # call to fix takes care of any necessary folddown
2327 ans = ans._fix(context)
2328 return ans
2330 def same_quantum(self, other):
2331 """Return True if self and other have the same exponent; otherwise
2332 return False.
2334 If either operand is a special value, the following rules are used:
2335 * return True if both operands are infinities
2336 * return True if both operands are NaNs
2337 * otherwise, return False.
2339 other = _convert_other(other, raiseit=True)
2340 if self._is_special or other._is_special:
2341 return (self.is_nan() and other.is_nan() or
2342 self.is_infinite() and other.is_infinite())
2343 return self._exp == other._exp
2345 def _rescale(self, exp, rounding):
2346 """Rescale self so that the exponent is exp, either by padding with zeros
2347 or by truncating digits, using the given rounding mode.
2349 Specials are returned without change. This operation is
2350 quiet: it raises no flags, and uses no information from the
2351 context.
2353 exp = exp to scale to (an integer)
2354 rounding = rounding mode
2356 if self._is_special:
2357 return Decimal(self)
2358 if not self:
2359 return _dec_from_triple(self._sign, '0', exp)
2361 if self._exp >= exp:
2362 # pad answer with zeros if necessary
2363 return _dec_from_triple(self._sign,
2364 self._int + '0'*(self._exp - exp), exp)
2366 # too many digits; round and lose data. If self.adjusted() <
2367 # exp-1, replace self by 10**(exp-1) before rounding
2368 digits = len(self._int) + self._exp - exp
2369 if digits < 0:
2370 self = _dec_from_triple(self._sign, '1', exp-1)
2371 digits = 0
2372 this_function = getattr(self, self._pick_rounding_function[rounding])
2373 changed = this_function(digits)
2374 coeff = self._int[:digits] or '0'
2375 if changed == 1:
2376 coeff = str(int(coeff)+1)
2377 return _dec_from_triple(self._sign, coeff, exp)
2379 def _round(self, places, rounding):
2380 """Round a nonzero, nonspecial Decimal to a fixed number of
2381 significant figures, using the given rounding mode.
2383 Infinities, NaNs and zeros are returned unaltered.
2385 This operation is quiet: it raises no flags, and uses no
2386 information from the context.
2389 if places <= 0:
2390 raise ValueError("argument should be at least 1 in _round")
2391 if self._is_special or not self:
2392 return Decimal(self)
2393 ans = self._rescale(self.adjusted()+1-places, rounding)
2394 # it can happen that the rescale alters the adjusted exponent;
2395 # for example when rounding 99.97 to 3 significant figures.
2396 # When this happens we end up with an extra 0 at the end of
2397 # the number; a second rescale fixes this.
2398 if ans.adjusted() != self.adjusted():
2399 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2400 return ans
2402 def to_integral_exact(self, rounding=None, context=None):
2403 """Rounds to a nearby integer.
2405 If no rounding mode is specified, take the rounding mode from
2406 the context. This method raises the Rounded and Inexact flags
2407 when appropriate.
2409 See also: to_integral_value, which does exactly the same as
2410 this method except that it doesn't raise Inexact or Rounded.
2412 if self._is_special:
2413 ans = self._check_nans(context=context)
2414 if ans:
2415 return ans
2416 return Decimal(self)
2417 if self._exp >= 0:
2418 return Decimal(self)
2419 if not self:
2420 return _dec_from_triple(self._sign, '0', 0)
2421 if context is None:
2422 context = getcontext()
2423 if rounding is None:
2424 rounding = context.rounding
2425 context._raise_error(Rounded)
2426 ans = self._rescale(0, rounding)
2427 if ans != self:
2428 context._raise_error(Inexact)
2429 return ans
2431 def to_integral_value(self, rounding=None, context=None):
2432 """Rounds to the nearest integer, without raising inexact, rounded."""
2433 if context is None:
2434 context = getcontext()
2435 if rounding is None:
2436 rounding = context.rounding
2437 if self._is_special:
2438 ans = self._check_nans(context=context)
2439 if ans:
2440 return ans
2441 return Decimal(self)
2442 if self._exp >= 0:
2443 return Decimal(self)
2444 else:
2445 return self._rescale(0, rounding)
2447 # the method name changed, but we provide also the old one, for compatibility
2448 to_integral = to_integral_value
2450 def sqrt(self, context=None):
2451 """Return the square root of self."""
2452 if context is None:
2453 context = getcontext()
2455 if self._is_special:
2456 ans = self._check_nans(context=context)
2457 if ans:
2458 return ans
2460 if self._isinfinity() and self._sign == 0:
2461 return Decimal(self)
2463 if not self:
2464 # exponent = self._exp // 2. sqrt(-0) = -0
2465 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2466 return ans._fix(context)
2468 if self._sign == 1:
2469 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2471 # At this point self represents a positive number. Let p be
2472 # the desired precision and express self in the form c*100**e
2473 # with c a positive real number and e an integer, c and e
2474 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2475 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2476 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2477 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2478 # the closest integer to sqrt(c) with the even integer chosen
2479 # in the case of a tie.
2481 # To ensure correct rounding in all cases, we use the
2482 # following trick: we compute the square root to an extra
2483 # place (precision p+1 instead of precision p), rounding down.
2484 # Then, if the result is inexact and its last digit is 0 or 5,
2485 # we increase the last digit to 1 or 6 respectively; if it's
2486 # exact we leave the last digit alone. Now the final round to
2487 # p places (or fewer in the case of underflow) will round
2488 # correctly and raise the appropriate flags.
2490 # use an extra digit of precision
2491 prec = context.prec+1
2493 # write argument in the form c*100**e where e = self._exp//2
2494 # is the 'ideal' exponent, to be used if the square root is
2495 # exactly representable. l is the number of 'digits' of c in
2496 # base 100, so that 100**(l-1) <= c < 100**l.
2497 op = _WorkRep(self)
2498 e = op.exp >> 1
2499 if op.exp & 1:
2500 c = op.int * 10
2501 l = (len(self._int) >> 1) + 1
2502 else:
2503 c = op.int
2504 l = len(self._int)+1 >> 1
2506 # rescale so that c has exactly prec base 100 'digits'
2507 shift = prec-l
2508 if shift >= 0:
2509 c *= 100**shift
2510 exact = True
2511 else:
2512 c, remainder = divmod(c, 100**-shift)
2513 exact = not remainder
2514 e -= shift
2516 # find n = floor(sqrt(c)) using Newton's method
2517 n = 10**prec
2518 while True:
2519 q = c//n
2520 if n <= q:
2521 break
2522 else:
2523 n = n + q >> 1
2524 exact = exact and n*n == c
2526 if exact:
2527 # result is exact; rescale to use ideal exponent e
2528 if shift >= 0:
2529 # assert n % 10**shift == 0
2530 n //= 10**shift
2531 else:
2532 n *= 10**-shift
2533 e += shift
2534 else:
2535 # result is not exact; fix last digit as described above
2536 if n % 5 == 0:
2537 n += 1
2539 ans = _dec_from_triple(0, str(n), e)
2541 # round, and fit to current context
2542 context = context._shallow_copy()
2543 rounding = context._set_rounding(ROUND_HALF_EVEN)
2544 ans = ans._fix(context)
2545 context.rounding = rounding
2547 return ans
2549 def max(self, other, context=None):
2550 """Returns the larger value.
2552 Like max(self, other) except if one is not a number, returns
2553 NaN (and signals if one is sNaN). Also rounds.
2555 other = _convert_other(other, raiseit=True)
2557 if context is None:
2558 context = getcontext()
2560 if self._is_special or other._is_special:
2561 # If one operand is a quiet NaN and the other is number, then the
2562 # number is always returned
2563 sn = self._isnan()
2564 on = other._isnan()
2565 if sn or on:
2566 if on == 1 and sn != 2:
2567 return self._fix_nan(context)
2568 if sn == 1 and on != 2:
2569 return other._fix_nan(context)
2570 return self._check_nans(other, context)
2572 c = self._cmp(other)
2573 if c == 0:
2574 # If both operands are finite and equal in numerical value
2575 # then an ordering is applied:
2577 # If the signs differ then max returns the operand with the
2578 # positive sign and min returns the operand with the negative sign
2580 # If the signs are the same then the exponent is used to select
2581 # the result. This is exactly the ordering used in compare_total.
2582 c = self.compare_total(other)
2584 if c == -1:
2585 ans = other
2586 else:
2587 ans = self
2589 return ans._fix(context)
2591 def min(self, other, context=None):
2592 """Returns the smaller value.
2594 Like min(self, other) except if one is not a number, returns
2595 NaN (and signals if one is sNaN). Also rounds.
2597 other = _convert_other(other, raiseit=True)
2599 if context is None:
2600 context = getcontext()
2602 if self._is_special or other._is_special:
2603 # If one operand is a quiet NaN and the other is number, then the
2604 # number is always returned
2605 sn = self._isnan()
2606 on = other._isnan()
2607 if sn or on:
2608 if on == 1 and sn != 2:
2609 return self._fix_nan(context)
2610 if sn == 1 and on != 2:
2611 return other._fix_nan(context)
2612 return self._check_nans(other, context)
2614 c = self._cmp(other)
2615 if c == 0:
2616 c = self.compare_total(other)
2618 if c == -1:
2619 ans = self
2620 else:
2621 ans = other
2623 return ans._fix(context)
2625 def _isinteger(self):
2626 """Returns whether self is an integer"""
2627 if self._is_special:
2628 return False
2629 if self._exp >= 0:
2630 return True
2631 rest = self._int[self._exp:]
2632 return rest == '0'*len(rest)
2634 def _iseven(self):
2635 """Returns True if self is even. Assumes self is an integer."""
2636 if not self or self._exp > 0:
2637 return True
2638 return self._int[-1+self._exp] in '02468'
2640 def adjusted(self):
2641 """Return the adjusted exponent of self"""
2642 try:
2643 return self._exp + len(self._int) - 1
2644 # If NaN or Infinity, self._exp is string
2645 except TypeError:
2646 return 0
2648 def canonical(self, context=None):
2649 """Returns the same Decimal object.
2651 As we do not have different encodings for the same number, the
2652 received object already is in its canonical form.
2654 return self
2656 def compare_signal(self, other, context=None):
2657 """Compares self to the other operand numerically.
2659 It's pretty much like compare(), but all NaNs signal, with signaling
2660 NaNs taking precedence over quiet NaNs.
2662 other = _convert_other(other, raiseit = True)
2663 ans = self._compare_check_nans(other, context)
2664 if ans:
2665 return ans
2666 return self.compare(other, context=context)
2668 def compare_total(self, other):
2669 """Compares self to other using the abstract representations.
2671 This is not like the standard compare, which use their numerical
2672 value. Note that a total ordering is defined for all possible abstract
2673 representations.
2675 # if one is negative and the other is positive, it's easy
2676 if self._sign and not other._sign:
2677 return Dec_n1
2678 if not self._sign and other._sign:
2679 return Dec_p1
2680 sign = self._sign
2682 # let's handle both NaN types
2683 self_nan = self._isnan()
2684 other_nan = other._isnan()
2685 if self_nan or other_nan:
2686 if self_nan == other_nan:
2687 if self._int < other._int:
2688 if sign:
2689 return Dec_p1
2690 else:
2691 return Dec_n1
2692 if self._int > other._int:
2693 if sign:
2694 return Dec_n1
2695 else:
2696 return Dec_p1
2697 return Dec_0
2699 if sign:
2700 if self_nan == 1:
2701 return Dec_n1
2702 if other_nan == 1:
2703 return Dec_p1
2704 if self_nan == 2:
2705 return Dec_n1
2706 if other_nan == 2:
2707 return Dec_p1
2708 else:
2709 if self_nan == 1:
2710 return Dec_p1
2711 if other_nan == 1:
2712 return Dec_n1
2713 if self_nan == 2:
2714 return Dec_p1
2715 if other_nan == 2:
2716 return Dec_n1
2718 if self < other:
2719 return Dec_n1
2720 if self > other:
2721 return Dec_p1
2723 if self._exp < other._exp:
2724 if sign:
2725 return Dec_p1
2726 else:
2727 return Dec_n1
2728 if self._exp > other._exp:
2729 if sign:
2730 return Dec_n1
2731 else:
2732 return Dec_p1
2733 return Dec_0
2736 def compare_total_mag(self, other):
2737 """Compares self to other using abstract repr., ignoring sign.
2739 Like compare_total, but with operand's sign ignored and assumed to be 0.
2741 s = self.copy_abs()
2742 o = other.copy_abs()
2743 return s.compare_total(o)
2745 def copy_abs(self):
2746 """Returns a copy with the sign set to 0. """
2747 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2749 def copy_negate(self):
2750 """Returns a copy with the sign inverted."""
2751 if self._sign:
2752 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2753 else:
2754 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2756 def copy_sign(self, other):
2757 """Returns self with the sign of other."""
2758 return _dec_from_triple(other._sign, self._int,
2759 self._exp, self._is_special)
2761 def exp(self, context=None):
2762 """Returns e ** self."""
2764 if context is None:
2765 context = getcontext()
2767 # exp(NaN) = NaN
2768 ans = self._check_nans(context=context)
2769 if ans:
2770 return ans
2772 # exp(-Infinity) = 0
2773 if self._isinfinity() == -1:
2774 return Dec_0
2776 # exp(0) = 1
2777 if not self:
2778 return Dec_p1
2780 # exp(Infinity) = Infinity
2781 if self._isinfinity() == 1:
2782 return Decimal(self)
2784 # the result is now guaranteed to be inexact (the true
2785 # mathematical result is transcendental). There's no need to
2786 # raise Rounded and Inexact here---they'll always be raised as
2787 # a result of the call to _fix.
2788 p = context.prec
2789 adj = self.adjusted()
2791 # we only need to do any computation for quite a small range
2792 # of adjusted exponents---for example, -29 <= adj <= 10 for
2793 # the default context. For smaller exponent the result is
2794 # indistinguishable from 1 at the given precision, while for
2795 # larger exponent the result either overflows or underflows.
2796 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2797 # overflow
2798 ans = _dec_from_triple(0, '1', context.Emax+1)
2799 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2800 # underflow to 0
2801 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2802 elif self._sign == 0 and adj < -p:
2803 # p+1 digits; final round will raise correct flags
2804 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2805 elif self._sign == 1 and adj < -p-1:
2806 # p+1 digits; final round will raise correct flags
2807 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2808 # general case
2809 else:
2810 op = _WorkRep(self)
2811 c, e = op.int, op.exp
2812 if op.sign == 1:
2813 c = -c
2815 # compute correctly rounded result: increase precision by
2816 # 3 digits at a time until we get an unambiguously
2817 # roundable result
2818 extra = 3
2819 while True:
2820 coeff, exp = _dexp(c, e, p+extra)
2821 if coeff % (5*10**(len(str(coeff))-p-1)):
2822 break
2823 extra += 3
2825 ans = _dec_from_triple(0, str(coeff), exp)
2827 # at this stage, ans should round correctly with *any*
2828 # rounding mode, not just with ROUND_HALF_EVEN
2829 context = context._shallow_copy()
2830 rounding = context._set_rounding(ROUND_HALF_EVEN)
2831 ans = ans._fix(context)
2832 context.rounding = rounding
2834 return ans
2836 def is_canonical(self):
2837 """Return True if self is canonical; otherwise return False.
2839 Currently, the encoding of a Decimal instance is always
2840 canonical, so this method returns True for any Decimal.
2842 return True
2844 def is_finite(self):
2845 """Return True if self is finite; otherwise return False.
2847 A Decimal instance is considered finite if it is neither
2848 infinite nor a NaN.
2850 return not self._is_special
2852 def is_infinite(self):
2853 """Return True if self is infinite; otherwise return False."""
2854 return self._exp == 'F'
2856 def is_nan(self):
2857 """Return True if self is a qNaN or sNaN; otherwise return False."""
2858 return self._exp in ('n', 'N')
2860 def is_normal(self, context=None):
2861 """Return True if self is a normal number; otherwise return False."""
2862 if self._is_special or not self:
2863 return False
2864 if context is None:
2865 context = getcontext()
2866 return context.Emin <= self.adjusted() <= context.Emax
2868 def is_qnan(self):
2869 """Return True if self is a quiet NaN; otherwise return False."""
2870 return self._exp == 'n'
2872 def is_signed(self):
2873 """Return True if self is negative; otherwise return False."""
2874 return self._sign == 1
2876 def is_snan(self):
2877 """Return True if self is a signaling NaN; otherwise return False."""
2878 return self._exp == 'N'
2880 def is_subnormal(self, context=None):
2881 """Return True if self is subnormal; otherwise return False."""
2882 if self._is_special or not self:
2883 return False
2884 if context is None:
2885 context = getcontext()
2886 return self.adjusted() < context.Emin
2888 def is_zero(self):
2889 """Return True if self is a zero; otherwise return False."""
2890 return not self._is_special and self._int == '0'
2892 def _ln_exp_bound(self):
2893 """Compute a lower bound for the adjusted exponent of self.ln().
2894 In other words, compute r such that self.ln() >= 10**r. Assumes
2895 that self is finite and positive and that self != 1.
2898 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2899 adj = self._exp + len(self._int) - 1
2900 if adj >= 1:
2901 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2902 return len(str(adj*23//10)) - 1
2903 if adj <= -2:
2904 # argument <= 0.1
2905 return len(str((-1-adj)*23//10)) - 1
2906 op = _WorkRep(self)
2907 c, e = op.int, op.exp
2908 if adj == 0:
2909 # 1 < self < 10
2910 num = str(c-10**-e)
2911 den = str(c)
2912 return len(num) - len(den) - (num < den)
2913 # adj == -1, 0.1 <= self < 1
2914 return e + len(str(10**-e - c)) - 1
2917 def ln(self, context=None):
2918 """Returns the natural (base e) logarithm of self."""
2920 if context is None:
2921 context = getcontext()
2923 # ln(NaN) = NaN
2924 ans = self._check_nans(context=context)
2925 if ans:
2926 return ans
2928 # ln(0.0) == -Infinity
2929 if not self:
2930 return negInf
2932 # ln(Infinity) = Infinity
2933 if self._isinfinity() == 1:
2934 return Inf
2936 # ln(1.0) == 0.0
2937 if self == Dec_p1:
2938 return Dec_0
2940 # ln(negative) raises InvalidOperation
2941 if self._sign == 1:
2942 return context._raise_error(InvalidOperation,
2943 'ln of a negative value')
2945 # result is irrational, so necessarily inexact
2946 op = _WorkRep(self)
2947 c, e = op.int, op.exp
2948 p = context.prec
2950 # correctly rounded result: repeatedly increase precision by 3
2951 # until we get an unambiguously roundable result
2952 places = p - self._ln_exp_bound() + 2 # at least p+3 places
2953 while True:
2954 coeff = _dlog(c, e, places)
2955 # assert len(str(abs(coeff)))-p >= 1
2956 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
2957 break
2958 places += 3
2959 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
2961 context = context._shallow_copy()
2962 rounding = context._set_rounding(ROUND_HALF_EVEN)
2963 ans = ans._fix(context)
2964 context.rounding = rounding
2965 return ans
2967 def _log10_exp_bound(self):
2968 """Compute a lower bound for the adjusted exponent of self.log10().
2969 In other words, find r such that self.log10() >= 10**r.
2970 Assumes that self is finite and positive and that self != 1.
2973 # For x >= 10 or x < 0.1 we only need a bound on the integer
2974 # part of log10(self), and this comes directly from the
2975 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
2976 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
2977 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
2979 adj = self._exp + len(self._int) - 1
2980 if adj >= 1:
2981 # self >= 10
2982 return len(str(adj))-1
2983 if adj <= -2:
2984 # self < 0.1
2985 return len(str(-1-adj))-1
2986 op = _WorkRep(self)
2987 c, e = op.int, op.exp
2988 if adj == 0:
2989 # 1 < self < 10
2990 num = str(c-10**-e)
2991 den = str(231*c)
2992 return len(num) - len(den) - (num < den) + 2
2993 # adj == -1, 0.1 <= self < 1
2994 num = str(10**-e-c)
2995 return len(num) + e - (num < "231") - 1
2997 def log10(self, context=None):
2998 """Returns the base 10 logarithm of self."""
3000 if context is None:
3001 context = getcontext()
3003 # log10(NaN) = NaN
3004 ans = self._check_nans(context=context)
3005 if ans:
3006 return ans
3008 # log10(0.0) == -Infinity
3009 if not self:
3010 return negInf
3012 # log10(Infinity) = Infinity
3013 if self._isinfinity() == 1:
3014 return Inf
3016 # log10(negative or -Infinity) raises InvalidOperation
3017 if self._sign == 1:
3018 return context._raise_error(InvalidOperation,
3019 'log10 of a negative value')
3021 # log10(10**n) = n
3022 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3023 # answer may need rounding
3024 ans = Decimal(self._exp + len(self._int) - 1)
3025 else:
3026 # result is irrational, so necessarily inexact
3027 op = _WorkRep(self)
3028 c, e = op.int, op.exp
3029 p = context.prec
3031 # correctly rounded result: repeatedly increase precision
3032 # until result is unambiguously roundable
3033 places = p-self._log10_exp_bound()+2
3034 while True:
3035 coeff = _dlog10(c, e, places)
3036 # assert len(str(abs(coeff)))-p >= 1
3037 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3038 break
3039 places += 3
3040 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3042 context = context._shallow_copy()
3043 rounding = context._set_rounding(ROUND_HALF_EVEN)
3044 ans = ans._fix(context)
3045 context.rounding = rounding
3046 return ans
3048 def logb(self, context=None):
3049 """ Returns the exponent of the magnitude of self's MSD.
3051 The result is the integer which is the exponent of the magnitude
3052 of the most significant digit of self (as though it were truncated
3053 to a single digit while maintaining the value of that digit and
3054 without limiting the resulting exponent).
3056 # logb(NaN) = NaN
3057 ans = self._check_nans(context=context)
3058 if ans:
3059 return ans
3061 if context is None:
3062 context = getcontext()
3064 # logb(+/-Inf) = +Inf
3065 if self._isinfinity():
3066 return Inf
3068 # logb(0) = -Inf, DivisionByZero
3069 if not self:
3070 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3072 # otherwise, simply return the adjusted exponent of self, as a
3073 # Decimal. Note that no attempt is made to fit the result
3074 # into the current context.
3075 return Decimal(self.adjusted())
3077 def _islogical(self):
3078 """Return True if self is a logical operand.
3080 For being logical, it must be a finite number with a sign of 0,
3081 an exponent of 0, and a coefficient whose digits must all be
3082 either 0 or 1.
3084 if self._sign != 0 or self._exp != 0:
3085 return False
3086 for dig in self._int:
3087 if dig not in '01':
3088 return False
3089 return True
3091 def _fill_logical(self, context, opa, opb):
3092 dif = context.prec - len(opa)
3093 if dif > 0:
3094 opa = '0'*dif + opa
3095 elif dif < 0:
3096 opa = opa[-context.prec:]
3097 dif = context.prec - len(opb)
3098 if dif > 0:
3099 opb = '0'*dif + opb
3100 elif dif < 0:
3101 opb = opb[-context.prec:]
3102 return opa, opb
3104 def logical_and(self, other, context=None):
3105 """Applies an 'and' operation between self and other's digits."""
3106 if context is None:
3107 context = getcontext()
3108 if not self._islogical() or not other._islogical():
3109 return context._raise_error(InvalidOperation)
3111 # fill to context.prec
3112 (opa, opb) = self._fill_logical(context, self._int, other._int)
3114 # make the operation, and clean starting zeroes
3115 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3116 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3118 def logical_invert(self, context=None):
3119 """Invert all its digits."""
3120 if context is None:
3121 context = getcontext()
3122 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3123 context)
3125 def logical_or(self, other, context=None):
3126 """Applies an 'or' operation between self and other's digits."""
3127 if context is None:
3128 context = getcontext()
3129 if not self._islogical() or not other._islogical():
3130 return context._raise_error(InvalidOperation)
3132 # fill to context.prec
3133 (opa, opb) = self._fill_logical(context, self._int, other._int)
3135 # make the operation, and clean starting zeroes
3136 result = "".join(str(int(a)|int(b)) for a,b in zip(opa,opb))
3137 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3139 def logical_xor(self, other, context=None):
3140 """Applies an 'xor' operation between self and other's digits."""
3141 if context is None:
3142 context = getcontext()
3143 if not self._islogical() or not other._islogical():
3144 return context._raise_error(InvalidOperation)
3146 # fill to context.prec
3147 (opa, opb) = self._fill_logical(context, self._int, other._int)
3149 # make the operation, and clean starting zeroes
3150 result = "".join(str(int(a)^int(b)) for a,b in zip(opa,opb))
3151 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3153 def max_mag(self, other, context=None):
3154 """Compares the values numerically with their sign ignored."""
3155 other = _convert_other(other, raiseit=True)
3157 if context is None:
3158 context = getcontext()
3160 if self._is_special or other._is_special:
3161 # If one operand is a quiet NaN and the other is number, then the
3162 # number is always returned
3163 sn = self._isnan()
3164 on = other._isnan()
3165 if sn or on:
3166 if on == 1 and sn != 2:
3167 return self._fix_nan(context)
3168 if sn == 1 and on != 2:
3169 return other._fix_nan(context)
3170 return self._check_nans(other, context)
3172 c = self.copy_abs()._cmp(other.copy_abs())
3173 if c == 0:
3174 c = self.compare_total(other)
3176 if c == -1:
3177 ans = other
3178 else:
3179 ans = self
3181 return ans._fix(context)
3183 def min_mag(self, other, context=None):
3184 """Compares the values numerically with their sign ignored."""
3185 other = _convert_other(other, raiseit=True)
3187 if context is None:
3188 context = getcontext()
3190 if self._is_special or other._is_special:
3191 # If one operand is a quiet NaN and the other is number, then the
3192 # number is always returned
3193 sn = self._isnan()
3194 on = other._isnan()
3195 if sn or on:
3196 if on == 1 and sn != 2:
3197 return self._fix_nan(context)
3198 if sn == 1 and on != 2:
3199 return other._fix_nan(context)
3200 return self._check_nans(other, context)
3202 c = self.copy_abs()._cmp(other.copy_abs())
3203 if c == 0:
3204 c = self.compare_total(other)
3206 if c == -1:
3207 ans = self
3208 else:
3209 ans = other
3211 return ans._fix(context)
3213 def next_minus(self, context=None):
3214 """Returns the largest representable number smaller than itself."""
3215 if context is None:
3216 context = getcontext()
3218 ans = self._check_nans(context=context)
3219 if ans:
3220 return ans
3222 if self._isinfinity() == -1:
3223 return negInf
3224 if self._isinfinity() == 1:
3225 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3227 context = context.copy()
3228 context._set_rounding(ROUND_FLOOR)
3229 context._ignore_all_flags()
3230 new_self = self._fix(context)
3231 if new_self != self:
3232 return new_self
3233 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3234 context)
3236 def next_plus(self, context=None):
3237 """Returns the smallest representable number larger than itself."""
3238 if context is None:
3239 context = getcontext()
3241 ans = self._check_nans(context=context)
3242 if ans:
3243 return ans
3245 if self._isinfinity() == 1:
3246 return Inf
3247 if self._isinfinity() == -1:
3248 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3250 context = context.copy()
3251 context._set_rounding(ROUND_CEILING)
3252 context._ignore_all_flags()
3253 new_self = self._fix(context)
3254 if new_self != self:
3255 return new_self
3256 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3257 context)
3259 def next_toward(self, other, context=None):
3260 """Returns the number closest to self, in the direction towards other.
3262 The result is the closest representable number to self
3263 (excluding self) that is in the direction towards other,
3264 unless both have the same value. If the two operands are
3265 numerically equal, then the result is a copy of self with the
3266 sign set to be the same as the sign of other.
3268 other = _convert_other(other, raiseit=True)
3270 if context is None:
3271 context = getcontext()
3273 ans = self._check_nans(other, context)
3274 if ans:
3275 return ans
3277 comparison = self._cmp(other)
3278 if comparison == 0:
3279 return self.copy_sign(other)
3281 if comparison == -1:
3282 ans = self.next_plus(context)
3283 else: # comparison == 1
3284 ans = self.next_minus(context)
3286 # decide which flags to raise using value of ans
3287 if ans._isinfinity():
3288 context._raise_error(Overflow,
3289 'Infinite result from next_toward',
3290 ans._sign)
3291 context._raise_error(Rounded)
3292 context._raise_error(Inexact)
3293 elif ans.adjusted() < context.Emin:
3294 context._raise_error(Underflow)
3295 context._raise_error(Subnormal)
3296 context._raise_error(Rounded)
3297 context._raise_error(Inexact)
3298 # if precision == 1 then we don't raise Clamped for a
3299 # result 0E-Etiny.
3300 if not ans:
3301 context._raise_error(Clamped)
3303 return ans
3305 def number_class(self, context=None):
3306 """Returns an indication of the class of self.
3308 The class is one of the following strings:
3309 sNaN
3311 -Infinity
3312 -Normal
3313 -Subnormal
3314 -Zero
3315 +Zero
3316 +Subnormal
3317 +Normal
3318 +Infinity
3320 if self.is_snan():
3321 return "sNaN"
3322 if self.is_qnan():
3323 return "NaN"
3324 inf = self._isinfinity()
3325 if inf == 1:
3326 return "+Infinity"
3327 if inf == -1:
3328 return "-Infinity"
3329 if self.is_zero():
3330 if self._sign:
3331 return "-Zero"
3332 else:
3333 return "+Zero"
3334 if context is None:
3335 context = getcontext()
3336 if self.is_subnormal(context=context):
3337 if self._sign:
3338 return "-Subnormal"
3339 else:
3340 return "+Subnormal"
3341 # just a normal, regular, boring number, :)
3342 if self._sign:
3343 return "-Normal"
3344 else:
3345 return "+Normal"
3347 def radix(self):
3348 """Just returns 10, as this is Decimal, :)"""
3349 return Decimal(10)
3351 def rotate(self, other, context=None):
3352 """Returns a rotated copy of self, value-of-other times."""
3353 if context is None:
3354 context = getcontext()
3356 ans = self._check_nans(other, context)
3357 if ans:
3358 return ans
3360 if other._exp != 0:
3361 return context._raise_error(InvalidOperation)
3362 if not (-context.prec <= int(other) <= context.prec):
3363 return context._raise_error(InvalidOperation)
3365 if self._isinfinity():
3366 return Decimal(self)
3368 # get values, pad if necessary
3369 torot = int(other)
3370 rotdig = self._int
3371 topad = context.prec - len(rotdig)
3372 if topad:
3373 rotdig = '0'*topad + rotdig
3375 # let's rotate!
3376 rotated = rotdig[torot:] + rotdig[:torot]
3377 return _dec_from_triple(self._sign,
3378 rotated.lstrip('0') or '0', self._exp)
3380 def scaleb (self, other, context=None):
3381 """Returns self operand after adding the second value to its exp."""
3382 if context is None:
3383 context = getcontext()
3385 ans = self._check_nans(other, context)
3386 if ans:
3387 return ans
3389 if other._exp != 0:
3390 return context._raise_error(InvalidOperation)
3391 liminf = -2 * (context.Emax + context.prec)
3392 limsup = 2 * (context.Emax + context.prec)
3393 if not (liminf <= int(other) <= limsup):
3394 return context._raise_error(InvalidOperation)
3396 if self._isinfinity():
3397 return Decimal(self)
3399 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3400 d = d._fix(context)
3401 return d
3403 def shift(self, other, context=None):
3404 """Returns a shifted copy of self, value-of-other times."""
3405 if context is None:
3406 context = getcontext()
3408 ans = self._check_nans(other, context)
3409 if ans:
3410 return ans
3412 if other._exp != 0:
3413 return context._raise_error(InvalidOperation)
3414 if not (-context.prec <= int(other) <= context.prec):
3415 return context._raise_error(InvalidOperation)
3417 if self._isinfinity():
3418 return Decimal(self)
3420 # get values, pad if necessary
3421 torot = int(other)
3422 if not torot:
3423 return Decimal(self)
3424 rotdig = self._int
3425 topad = context.prec - len(rotdig)
3426 if topad:
3427 rotdig = '0'*topad + rotdig
3429 # let's shift!
3430 if torot < 0:
3431 rotated = rotdig[:torot]
3432 else:
3433 rotated = rotdig + '0'*torot
3434 rotated = rotated[-context.prec:]
3436 return _dec_from_triple(self._sign,
3437 rotated.lstrip('0') or '0', self._exp)
3439 # Support for pickling, copy, and deepcopy
3440 def __reduce__(self):
3441 return (self.__class__, (str(self),))
3443 def __copy__(self):
3444 if type(self) == Decimal:
3445 return self # I'm immutable; therefore I am my own clone
3446 return self.__class__(str(self))
3448 def __deepcopy__(self, memo):
3449 if type(self) == Decimal:
3450 return self # My components are also immutable
3451 return self.__class__(str(self))
3453 # PEP 3101 support. See also _parse_format_specifier and _format_align
3454 def __format__(self, specifier, context=None):
3455 """Format a Decimal instance according to the given specifier.
3457 The specifier should be a standard format specifier, with the
3458 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3459 'F', 'g', 'G', and '%' are supported. If the formatting type
3460 is omitted it defaults to 'g' or 'G', depending on the value
3461 of context.capitals.
3463 At this time the 'n' format specifier type (which is supposed
3464 to use the current locale) is not supported.
3467 # Note: PEP 3101 says that if the type is not present then
3468 # there should be at least one digit after the decimal point.
3469 # We take the liberty of ignoring this requirement for
3470 # Decimal---it's presumably there to make sure that
3471 # format(float, '') behaves similarly to str(float).
3472 if context is None:
3473 context = getcontext()
3475 spec = _parse_format_specifier(specifier)
3477 # special values don't care about the type or precision...
3478 if self._is_special:
3479 return _format_align(str(self), spec)
3481 # a type of None defaults to 'g' or 'G', depending on context
3482 # if type is '%', adjust exponent of self accordingly
3483 if spec['type'] is None:
3484 spec['type'] = ['g', 'G'][context.capitals]
3485 elif spec['type'] == '%':
3486 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3488 # round if necessary, taking rounding mode from the context
3489 rounding = context.rounding
3490 precision = spec['precision']
3491 if precision is not None:
3492 if spec['type'] in 'eE':
3493 self = self._round(precision+1, rounding)
3494 elif spec['type'] in 'gG':
3495 if len(self._int) > precision:
3496 self = self._round(precision, rounding)
3497 elif spec['type'] in 'fF%':
3498 self = self._rescale(-precision, rounding)
3499 # special case: zeros with a positive exponent can't be
3500 # represented in fixed point; rescale them to 0e0.
3501 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3502 self = self._rescale(0, rounding)
3504 # figure out placement of the decimal point
3505 leftdigits = self._exp + len(self._int)
3506 if spec['type'] in 'fF%':
3507 dotplace = leftdigits
3508 elif spec['type'] in 'eE':
3509 if not self and precision is not None:
3510 dotplace = 1 - precision
3511 else:
3512 dotplace = 1
3513 elif spec['type'] in 'gG':
3514 if self._exp <= 0 and leftdigits > -6:
3515 dotplace = leftdigits
3516 else:
3517 dotplace = 1
3519 # figure out main part of numeric string...
3520 if dotplace <= 0:
3521 num = '0.' + '0'*(-dotplace) + self._int
3522 elif dotplace >= len(self._int):
3523 # make sure we're not padding a '0' with extra zeros on the right
3524 assert dotplace==len(self._int) or self._int != '0'
3525 num = self._int + '0'*(dotplace-len(self._int))
3526 else:
3527 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3529 # ...then the trailing exponent, or trailing '%'
3530 if leftdigits != dotplace or spec['type'] in 'eE':
3531 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3532 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3533 elif spec['type'] == '%':
3534 num = num + '%'
3536 # add sign
3537 if self._sign == 1:
3538 num = '-' + num
3539 return _format_align(num, spec)
3542 def _dec_from_triple(sign, coefficient, exponent, special=False):
3543 """Create a decimal instance directly, without any validation,
3544 normalization (e.g. removal of leading zeros) or argument
3545 conversion.
3547 This function is for *internal use only*.
3550 self = object.__new__(Decimal)
3551 self._sign = sign
3552 self._int = coefficient
3553 self._exp = exponent
3554 self._is_special = special
3556 return self
3558 ##### Context class #######################################################
3561 # get rounding method function:
3562 rounding_functions = [name for name in Decimal.__dict__.keys()
3563 if name.startswith('_round_')]
3564 for name in rounding_functions:
3565 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3566 globalname = name[1:].upper()
3567 val = globals()[globalname]
3568 Decimal._pick_rounding_function[val] = name
3570 del name, val, globalname, rounding_functions
3572 class _ContextManager(object):
3573 """Context manager class to support localcontext().
3575 Sets a copy of the supplied context in __enter__() and restores
3576 the previous decimal context in __exit__()
3578 def __init__(self, new_context):
3579 self.new_context = new_context.copy()
3580 def __enter__(self):
3581 self.saved_context = getcontext()
3582 setcontext(self.new_context)
3583 return self.new_context
3584 def __exit__(self, t, v, tb):
3585 setcontext(self.saved_context)
3587 class Context(object):
3588 """Contains the context for a Decimal instance.
3590 Contains:
3591 prec - precision (for use in rounding, division, square roots..)
3592 rounding - rounding type (how you round)
3593 traps - If traps[exception] = 1, then the exception is
3594 raised when it is caused. Otherwise, a value is
3595 substituted in.
3596 flags - When an exception is caused, flags[exception] is set.
3597 (Whether or not the trap_enabler is set)
3598 Should be reset by user of Decimal instance.
3599 Emin - Minimum exponent
3600 Emax - Maximum exponent
3601 capitals - If 1, 1*10^1 is printed as 1E+1.
3602 If 0, printed as 1e1
3603 _clamp - If 1, change exponents if too high (Default 0)
3606 def __init__(self, prec=None, rounding=None,
3607 traps=None, flags=None,
3608 Emin=None, Emax=None,
3609 capitals=None, _clamp=0,
3610 _ignored_flags=None):
3611 if flags is None:
3612 flags = []
3613 if _ignored_flags is None:
3614 _ignored_flags = []
3615 if not isinstance(flags, dict):
3616 flags = dict([(s, int(s in flags)) for s in _signals])
3617 del s
3618 if traps is not None and not isinstance(traps, dict):
3619 traps = dict([(s, int(s in traps)) for s in _signals])
3620 del s
3621 for name, val in locals().items():
3622 if val is None:
3623 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3624 else:
3625 setattr(self, name, val)
3626 del self.self
3628 def __repr__(self):
3629 """Show the current context."""
3630 s = []
3631 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3632 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3633 % vars(self))
3634 names = [f.__name__ for f, v in self.flags.items() if v]
3635 s.append('flags=[' + ', '.join(names) + ']')
3636 names = [t.__name__ for t, v in self.traps.items() if v]
3637 s.append('traps=[' + ', '.join(names) + ']')
3638 return ', '.join(s) + ')'
3640 def clear_flags(self):
3641 """Reset all flags to zero"""
3642 for flag in self.flags:
3643 self.flags[flag] = 0
3645 def _shallow_copy(self):
3646 """Returns a shallow copy from self."""
3647 nc = Context(self.prec, self.rounding, self.traps,
3648 self.flags, self.Emin, self.Emax,
3649 self.capitals, self._clamp, self._ignored_flags)
3650 return nc
3652 def copy(self):
3653 """Returns a deep copy from self."""
3654 nc = Context(self.prec, self.rounding, self.traps.copy(),
3655 self.flags.copy(), self.Emin, self.Emax,
3656 self.capitals, self._clamp, self._ignored_flags)
3657 return nc
3658 __copy__ = copy
3660 def _raise_error(self, condition, explanation = None, *args):
3661 """Handles an error
3663 If the flag is in _ignored_flags, returns the default response.
3664 Otherwise, it sets the flag, then, if the corresponding
3665 trap_enabler is set, it reaises the exception. Otherwise, it returns
3666 the default value after setting the flag.
3668 error = _condition_map.get(condition, condition)
3669 if error in self._ignored_flags:
3670 # Don't touch the flag
3671 return error().handle(self, *args)
3673 self.flags[error] = 1
3674 if not self.traps[error]:
3675 # The errors define how to handle themselves.
3676 return condition().handle(self, *args)
3678 # Errors should only be risked on copies of the context
3679 # self._ignored_flags = []
3680 raise error(explanation)
3682 def _ignore_all_flags(self):
3683 """Ignore all flags, if they are raised"""
3684 return self._ignore_flags(*_signals)
3686 def _ignore_flags(self, *flags):
3687 """Ignore the flags, if they are raised"""
3688 # Do not mutate-- This way, copies of a context leave the original
3689 # alone.
3690 self._ignored_flags = (self._ignored_flags + list(flags))
3691 return list(flags)
3693 def _regard_flags(self, *flags):
3694 """Stop ignoring the flags, if they are raised"""
3695 if flags and isinstance(flags[0], (tuple,list)):
3696 flags = flags[0]
3697 for flag in flags:
3698 self._ignored_flags.remove(flag)
3700 def __hash__(self):
3701 """A Context cannot be hashed."""
3702 # We inherit object.__hash__, so we must deny this explicitly
3703 raise TypeError("Cannot hash a Context.")
3705 def Etiny(self):
3706 """Returns Etiny (= Emin - prec + 1)"""
3707 return int(self.Emin - self.prec + 1)
3709 def Etop(self):
3710 """Returns maximum exponent (= Emax - prec + 1)"""
3711 return int(self.Emax - self.prec + 1)
3713 def _set_rounding(self, type):
3714 """Sets the rounding type.
3716 Sets the rounding type, and returns the current (previous)
3717 rounding type. Often used like:
3719 context = context.copy()
3720 # so you don't change the calling context
3721 # if an error occurs in the middle.
3722 rounding = context._set_rounding(ROUND_UP)
3723 val = self.__sub__(other, context=context)
3724 context._set_rounding(rounding)
3726 This will make it round up for that operation.
3728 rounding = self.rounding
3729 self.rounding= type
3730 return rounding
3732 def create_decimal(self, num='0'):
3733 """Creates a new Decimal instance but using self as context.
3735 This method implements the to-number operation of the
3736 IBM Decimal specification."""
3738 if isinstance(num, basestring) and num != num.strip():
3739 return self._raise_error(ConversionSyntax,
3740 "no trailing or leading whitespace is "
3741 "permitted.")
3743 d = Decimal(num, context=self)
3744 if d._isnan() and len(d._int) > self.prec - self._clamp:
3745 return self._raise_error(ConversionSyntax,
3746 "diagnostic info too long in NaN")
3747 return d._fix(self)
3749 # Methods
3750 def abs(self, a):
3751 """Returns the absolute value of the operand.
3753 If the operand is negative, the result is the same as using the minus
3754 operation on the operand. Otherwise, the result is the same as using
3755 the plus operation on the operand.
3757 >>> ExtendedContext.abs(Decimal('2.1'))
3758 Decimal('2.1')
3759 >>> ExtendedContext.abs(Decimal('-100'))
3760 Decimal('100')
3761 >>> ExtendedContext.abs(Decimal('101.5'))
3762 Decimal('101.5')
3763 >>> ExtendedContext.abs(Decimal('-101.5'))
3764 Decimal('101.5')
3766 return a.__abs__(context=self)
3768 def add(self, a, b):
3769 """Return the sum of the two operands.
3771 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3772 Decimal('19.00')
3773 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3774 Decimal('1.02E+4')
3776 return a.__add__(b, context=self)
3778 def _apply(self, a):
3779 return str(a._fix(self))
3781 def canonical(self, a):
3782 """Returns the same Decimal object.
3784 As we do not have different encodings for the same number, the
3785 received object already is in its canonical form.
3787 >>> ExtendedContext.canonical(Decimal('2.50'))
3788 Decimal('2.50')
3790 return a.canonical(context=self)
3792 def compare(self, a, b):
3793 """Compares values numerically.
3795 If the signs of the operands differ, a value representing each operand
3796 ('-1' if the operand is less than zero, '0' if the operand is zero or
3797 negative zero, or '1' if the operand is greater than zero) is used in
3798 place of that operand for the comparison instead of the actual
3799 operand.
3801 The comparison is then effected by subtracting the second operand from
3802 the first and then returning a value according to the result of the
3803 subtraction: '-1' if the result is less than zero, '0' if the result is
3804 zero or negative zero, or '1' if the result is greater than zero.
3806 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3807 Decimal('-1')
3808 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3809 Decimal('0')
3810 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3811 Decimal('0')
3812 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3813 Decimal('1')
3814 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3815 Decimal('1')
3816 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3817 Decimal('-1')
3819 return a.compare(b, context=self)
3821 def compare_signal(self, a, b):
3822 """Compares the values of the two operands numerically.
3824 It's pretty much like compare(), but all NaNs signal, with signaling
3825 NaNs taking precedence over quiet NaNs.
3827 >>> c = ExtendedContext
3828 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3829 Decimal('-1')
3830 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3831 Decimal('0')
3832 >>> c.flags[InvalidOperation] = 0
3833 >>> print c.flags[InvalidOperation]
3835 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3836 Decimal('NaN')
3837 >>> print c.flags[InvalidOperation]
3839 >>> c.flags[InvalidOperation] = 0
3840 >>> print c.flags[InvalidOperation]
3842 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3843 Decimal('NaN')
3844 >>> print c.flags[InvalidOperation]
3847 return a.compare_signal(b, context=self)
3849 def compare_total(self, a, b):
3850 """Compares two operands using their abstract representation.
3852 This is not like the standard compare, which use their numerical
3853 value. Note that a total ordering is defined for all possible abstract
3854 representations.
3856 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3857 Decimal('-1')
3858 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3859 Decimal('-1')
3860 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3861 Decimal('-1')
3862 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3863 Decimal('0')
3864 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3865 Decimal('1')
3866 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3867 Decimal('-1')
3869 return a.compare_total(b)
3871 def compare_total_mag(self, a, b):
3872 """Compares two operands using their abstract representation ignoring sign.
3874 Like compare_total, but with operand's sign ignored and assumed to be 0.
3876 return a.compare_total_mag(b)
3878 def copy_abs(self, a):
3879 """Returns a copy of the operand with the sign set to 0.
3881 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3882 Decimal('2.1')
3883 >>> ExtendedContext.copy_abs(Decimal('-100'))
3884 Decimal('100')
3886 return a.copy_abs()
3888 def copy_decimal(self, a):
3889 """Returns a copy of the decimal objet.
3891 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3892 Decimal('2.1')
3893 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3894 Decimal('-1.00')
3896 return Decimal(a)
3898 def copy_negate(self, a):
3899 """Returns a copy of the operand with the sign inverted.
3901 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3902 Decimal('-101.5')
3903 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3904 Decimal('101.5')
3906 return a.copy_negate()
3908 def copy_sign(self, a, b):
3909 """Copies the second operand's sign to the first one.
3911 In detail, it returns a copy of the first operand with the sign
3912 equal to the sign of the second operand.
3914 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3915 Decimal('1.50')
3916 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3917 Decimal('1.50')
3918 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3919 Decimal('-1.50')
3920 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3921 Decimal('-1.50')
3923 return a.copy_sign(b)
3925 def divide(self, a, b):
3926 """Decimal division in a specified context.
3928 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
3929 Decimal('0.333333333')
3930 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
3931 Decimal('0.666666667')
3932 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
3933 Decimal('2.5')
3934 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
3935 Decimal('0.1')
3936 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
3937 Decimal('1')
3938 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
3939 Decimal('4.00')
3940 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
3941 Decimal('1.20')
3942 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
3943 Decimal('10')
3944 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
3945 Decimal('1000')
3946 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
3947 Decimal('1.20E+6')
3949 return a.__div__(b, context=self)
3951 def divide_int(self, a, b):
3952 """Divides two numbers and returns the integer part of the result.
3954 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
3955 Decimal('0')
3956 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
3957 Decimal('3')
3958 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
3959 Decimal('3')
3961 return a.__floordiv__(b, context=self)
3963 def divmod(self, a, b):
3964 return a.__divmod__(b, context=self)
3966 def exp(self, a):
3967 """Returns e ** a.
3969 >>> c = ExtendedContext.copy()
3970 >>> c.Emin = -999
3971 >>> c.Emax = 999
3972 >>> c.exp(Decimal('-Infinity'))
3973 Decimal('0')
3974 >>> c.exp(Decimal('-1'))
3975 Decimal('0.367879441')
3976 >>> c.exp(Decimal('0'))
3977 Decimal('1')
3978 >>> c.exp(Decimal('1'))
3979 Decimal('2.71828183')
3980 >>> c.exp(Decimal('0.693147181'))
3981 Decimal('2.00000000')
3982 >>> c.exp(Decimal('+Infinity'))
3983 Decimal('Infinity')
3985 return a.exp(context=self)
3987 def fma(self, a, b, c):
3988 """Returns a multiplied by b, plus c.
3990 The first two operands are multiplied together, using multiply,
3991 the third operand is then added to the result of that
3992 multiplication, using add, all with only one final rounding.
3994 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
3995 Decimal('22')
3996 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
3997 Decimal('-8')
3998 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
3999 Decimal('1.38435736E+12')
4001 return a.fma(b, c, context=self)
4003 def is_canonical(self, a):
4004 """Return True if the operand is canonical; otherwise return False.
4006 Currently, the encoding of a Decimal instance is always
4007 canonical, so this method returns True for any Decimal.
4009 >>> ExtendedContext.is_canonical(Decimal('2.50'))
4010 True
4012 return a.is_canonical()
4014 def is_finite(self, a):
4015 """Return True if the operand is finite; otherwise return False.
4017 A Decimal instance is considered finite if it is neither
4018 infinite nor a NaN.
4020 >>> ExtendedContext.is_finite(Decimal('2.50'))
4021 True
4022 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4023 True
4024 >>> ExtendedContext.is_finite(Decimal('0'))
4025 True
4026 >>> ExtendedContext.is_finite(Decimal('Inf'))
4027 False
4028 >>> ExtendedContext.is_finite(Decimal('NaN'))
4029 False
4031 return a.is_finite()
4033 def is_infinite(self, a):
4034 """Return True if the operand is infinite; otherwise return False.
4036 >>> ExtendedContext.is_infinite(Decimal('2.50'))
4037 False
4038 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4039 True
4040 >>> ExtendedContext.is_infinite(Decimal('NaN'))
4041 False
4043 return a.is_infinite()
4045 def is_nan(self, a):
4046 """Return True if the operand is a qNaN or sNaN;
4047 otherwise return False.
4049 >>> ExtendedContext.is_nan(Decimal('2.50'))
4050 False
4051 >>> ExtendedContext.is_nan(Decimal('NaN'))
4052 True
4053 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4054 True
4056 return a.is_nan()
4058 def is_normal(self, a):
4059 """Return True if the operand is a normal number;
4060 otherwise return False.
4062 >>> c = ExtendedContext.copy()
4063 >>> c.Emin = -999
4064 >>> c.Emax = 999
4065 >>> c.is_normal(Decimal('2.50'))
4066 True
4067 >>> c.is_normal(Decimal('0.1E-999'))
4068 False
4069 >>> c.is_normal(Decimal('0.00'))
4070 False
4071 >>> c.is_normal(Decimal('-Inf'))
4072 False
4073 >>> c.is_normal(Decimal('NaN'))
4074 False
4076 return a.is_normal(context=self)
4078 def is_qnan(self, a):
4079 """Return True if the operand is a quiet NaN; otherwise return False.
4081 >>> ExtendedContext.is_qnan(Decimal('2.50'))
4082 False
4083 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4084 True
4085 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4086 False
4088 return a.is_qnan()
4090 def is_signed(self, a):
4091 """Return True if the operand is negative; otherwise return False.
4093 >>> ExtendedContext.is_signed(Decimal('2.50'))
4094 False
4095 >>> ExtendedContext.is_signed(Decimal('-12'))
4096 True
4097 >>> ExtendedContext.is_signed(Decimal('-0'))
4098 True
4100 return a.is_signed()
4102 def is_snan(self, a):
4103 """Return True if the operand is a signaling NaN;
4104 otherwise return False.
4106 >>> ExtendedContext.is_snan(Decimal('2.50'))
4107 False
4108 >>> ExtendedContext.is_snan(Decimal('NaN'))
4109 False
4110 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4111 True
4113 return a.is_snan()
4115 def is_subnormal(self, a):
4116 """Return True if the operand is subnormal; otherwise return False.
4118 >>> c = ExtendedContext.copy()
4119 >>> c.Emin = -999
4120 >>> c.Emax = 999
4121 >>> c.is_subnormal(Decimal('2.50'))
4122 False
4123 >>> c.is_subnormal(Decimal('0.1E-999'))
4124 True
4125 >>> c.is_subnormal(Decimal('0.00'))
4126 False
4127 >>> c.is_subnormal(Decimal('-Inf'))
4128 False
4129 >>> c.is_subnormal(Decimal('NaN'))
4130 False
4132 return a.is_subnormal(context=self)
4134 def is_zero(self, a):
4135 """Return True if the operand is a zero; otherwise return False.
4137 >>> ExtendedContext.is_zero(Decimal('0'))
4138 True
4139 >>> ExtendedContext.is_zero(Decimal('2.50'))
4140 False
4141 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4142 True
4144 return a.is_zero()
4146 def ln(self, a):
4147 """Returns the natural (base e) logarithm of the operand.
4149 >>> c = ExtendedContext.copy()
4150 >>> c.Emin = -999
4151 >>> c.Emax = 999
4152 >>> c.ln(Decimal('0'))
4153 Decimal('-Infinity')
4154 >>> c.ln(Decimal('1.000'))
4155 Decimal('0')
4156 >>> c.ln(Decimal('2.71828183'))
4157 Decimal('1.00000000')
4158 >>> c.ln(Decimal('10'))
4159 Decimal('2.30258509')
4160 >>> c.ln(Decimal('+Infinity'))
4161 Decimal('Infinity')
4163 return a.ln(context=self)
4165 def log10(self, a):
4166 """Returns the base 10 logarithm of the operand.
4168 >>> c = ExtendedContext.copy()
4169 >>> c.Emin = -999
4170 >>> c.Emax = 999
4171 >>> c.log10(Decimal('0'))
4172 Decimal('-Infinity')
4173 >>> c.log10(Decimal('0.001'))
4174 Decimal('-3')
4175 >>> c.log10(Decimal('1.000'))
4176 Decimal('0')
4177 >>> c.log10(Decimal('2'))
4178 Decimal('0.301029996')
4179 >>> c.log10(Decimal('10'))
4180 Decimal('1')
4181 >>> c.log10(Decimal('70'))
4182 Decimal('1.84509804')
4183 >>> c.log10(Decimal('+Infinity'))
4184 Decimal('Infinity')
4186 return a.log10(context=self)
4188 def logb(self, a):
4189 """ Returns the exponent of the magnitude of the operand's MSD.
4191 The result is the integer which is the exponent of the magnitude
4192 of the most significant digit of the operand (as though the
4193 operand were truncated to a single digit while maintaining the
4194 value of that digit and without limiting the resulting exponent).
4196 >>> ExtendedContext.logb(Decimal('250'))
4197 Decimal('2')
4198 >>> ExtendedContext.logb(Decimal('2.50'))
4199 Decimal('0')
4200 >>> ExtendedContext.logb(Decimal('0.03'))
4201 Decimal('-2')
4202 >>> ExtendedContext.logb(Decimal('0'))
4203 Decimal('-Infinity')
4205 return a.logb(context=self)
4207 def logical_and(self, a, b):
4208 """Applies the logical operation 'and' between each operand's digits.
4210 The operands must be both logical numbers.
4212 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4213 Decimal('0')
4214 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4215 Decimal('0')
4216 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4217 Decimal('0')
4218 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4219 Decimal('1')
4220 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4221 Decimal('1000')
4222 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4223 Decimal('10')
4225 return a.logical_and(b, context=self)
4227 def logical_invert(self, a):
4228 """Invert all the digits in the operand.
4230 The operand must be a logical number.
4232 >>> ExtendedContext.logical_invert(Decimal('0'))
4233 Decimal('111111111')
4234 >>> ExtendedContext.logical_invert(Decimal('1'))
4235 Decimal('111111110')
4236 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4237 Decimal('0')
4238 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4239 Decimal('10101010')
4241 return a.logical_invert(context=self)
4243 def logical_or(self, a, b):
4244 """Applies the logical operation 'or' between each operand's digits.
4246 The operands must be both logical numbers.
4248 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4249 Decimal('0')
4250 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4251 Decimal('1')
4252 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4253 Decimal('1')
4254 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4255 Decimal('1')
4256 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4257 Decimal('1110')
4258 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4259 Decimal('1110')
4261 return a.logical_or(b, context=self)
4263 def logical_xor(self, a, b):
4264 """Applies the logical operation 'xor' between each operand's digits.
4266 The operands must be both logical numbers.
4268 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4269 Decimal('0')
4270 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4271 Decimal('1')
4272 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4273 Decimal('1')
4274 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4275 Decimal('0')
4276 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4277 Decimal('110')
4278 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4279 Decimal('1101')
4281 return a.logical_xor(b, context=self)
4283 def max(self, a,b):
4284 """max compares two values numerically and returns the maximum.
4286 If either operand is a NaN then the general rules apply.
4287 Otherwise, the operands are compared as though by the compare
4288 operation. If they are numerically equal then the left-hand operand
4289 is chosen as the result. Otherwise the maximum (closer to positive
4290 infinity) of the two operands is chosen as the result.
4292 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4293 Decimal('3')
4294 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4295 Decimal('3')
4296 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4297 Decimal('1')
4298 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4299 Decimal('7')
4301 return a.max(b, context=self)
4303 def max_mag(self, a, b):
4304 """Compares the values numerically with their sign ignored."""
4305 return a.max_mag(b, context=self)
4307 def min(self, a,b):
4308 """min compares two values numerically and returns the minimum.
4310 If either operand is a NaN then the general rules apply.
4311 Otherwise, the operands are compared as though by the compare
4312 operation. If they are numerically equal then the left-hand operand
4313 is chosen as the result. Otherwise the minimum (closer to negative
4314 infinity) of the two operands is chosen as the result.
4316 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4317 Decimal('2')
4318 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4319 Decimal('-10')
4320 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4321 Decimal('1.0')
4322 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4323 Decimal('7')
4325 return a.min(b, context=self)
4327 def min_mag(self, a, b):
4328 """Compares the values numerically with their sign ignored."""
4329 return a.min_mag(b, context=self)
4331 def minus(self, a):
4332 """Minus corresponds to unary prefix minus in Python.
4334 The operation is evaluated using the same rules as subtract; the
4335 operation minus(a) is calculated as subtract('0', a) where the '0'
4336 has the same exponent as the operand.
4338 >>> ExtendedContext.minus(Decimal('1.3'))
4339 Decimal('-1.3')
4340 >>> ExtendedContext.minus(Decimal('-1.3'))
4341 Decimal('1.3')
4343 return a.__neg__(context=self)
4345 def multiply(self, a, b):
4346 """multiply multiplies two operands.
4348 If either operand is a special value then the general rules apply.
4349 Otherwise, the operands are multiplied together ('long multiplication'),
4350 resulting in a number which may be as long as the sum of the lengths
4351 of the two operands.
4353 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4354 Decimal('3.60')
4355 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4356 Decimal('21')
4357 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4358 Decimal('0.72')
4359 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4360 Decimal('-0.0')
4361 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4362 Decimal('4.28135971E+11')
4364 return a.__mul__(b, context=self)
4366 def next_minus(self, a):
4367 """Returns the largest representable number smaller than a.
4369 >>> c = ExtendedContext.copy()
4370 >>> c.Emin = -999
4371 >>> c.Emax = 999
4372 >>> ExtendedContext.next_minus(Decimal('1'))
4373 Decimal('0.999999999')
4374 >>> c.next_minus(Decimal('1E-1007'))
4375 Decimal('0E-1007')
4376 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4377 Decimal('-1.00000004')
4378 >>> c.next_minus(Decimal('Infinity'))
4379 Decimal('9.99999999E+999')
4381 return a.next_minus(context=self)
4383 def next_plus(self, a):
4384 """Returns the smallest representable number larger than a.
4386 >>> c = ExtendedContext.copy()
4387 >>> c.Emin = -999
4388 >>> c.Emax = 999
4389 >>> ExtendedContext.next_plus(Decimal('1'))
4390 Decimal('1.00000001')
4391 >>> c.next_plus(Decimal('-1E-1007'))
4392 Decimal('-0E-1007')
4393 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4394 Decimal('-1.00000002')
4395 >>> c.next_plus(Decimal('-Infinity'))
4396 Decimal('-9.99999999E+999')
4398 return a.next_plus(context=self)
4400 def next_toward(self, a, b):
4401 """Returns the number closest to a, in direction towards b.
4403 The result is the closest representable number from the first
4404 operand (but not the first operand) that is in the direction
4405 towards the second operand, unless the operands have the same
4406 value.
4408 >>> c = ExtendedContext.copy()
4409 >>> c.Emin = -999
4410 >>> c.Emax = 999
4411 >>> c.next_toward(Decimal('1'), Decimal('2'))
4412 Decimal('1.00000001')
4413 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4414 Decimal('-0E-1007')
4415 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4416 Decimal('-1.00000002')
4417 >>> c.next_toward(Decimal('1'), Decimal('0'))
4418 Decimal('0.999999999')
4419 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4420 Decimal('0E-1007')
4421 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4422 Decimal('-1.00000004')
4423 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4424 Decimal('-0.00')
4426 return a.next_toward(b, context=self)
4428 def normalize(self, a):
4429 """normalize reduces an operand to its simplest form.
4431 Essentially a plus operation with all trailing zeros removed from the
4432 result.
4434 >>> ExtendedContext.normalize(Decimal('2.1'))
4435 Decimal('2.1')
4436 >>> ExtendedContext.normalize(Decimal('-2.0'))
4437 Decimal('-2')
4438 >>> ExtendedContext.normalize(Decimal('1.200'))
4439 Decimal('1.2')
4440 >>> ExtendedContext.normalize(Decimal('-120'))
4441 Decimal('-1.2E+2')
4442 >>> ExtendedContext.normalize(Decimal('120.00'))
4443 Decimal('1.2E+2')
4444 >>> ExtendedContext.normalize(Decimal('0.00'))
4445 Decimal('0')
4447 return a.normalize(context=self)
4449 def number_class(self, a):
4450 """Returns an indication of the class of the operand.
4452 The class is one of the following strings:
4453 -sNaN
4454 -NaN
4455 -Infinity
4456 -Normal
4457 -Subnormal
4458 -Zero
4459 +Zero
4460 +Subnormal
4461 +Normal
4462 +Infinity
4464 >>> c = Context(ExtendedContext)
4465 >>> c.Emin = -999
4466 >>> c.Emax = 999
4467 >>> c.number_class(Decimal('Infinity'))
4468 '+Infinity'
4469 >>> c.number_class(Decimal('1E-10'))
4470 '+Normal'
4471 >>> c.number_class(Decimal('2.50'))
4472 '+Normal'
4473 >>> c.number_class(Decimal('0.1E-999'))
4474 '+Subnormal'
4475 >>> c.number_class(Decimal('0'))
4476 '+Zero'
4477 >>> c.number_class(Decimal('-0'))
4478 '-Zero'
4479 >>> c.number_class(Decimal('-0.1E-999'))
4480 '-Subnormal'
4481 >>> c.number_class(Decimal('-1E-10'))
4482 '-Normal'
4483 >>> c.number_class(Decimal('-2.50'))
4484 '-Normal'
4485 >>> c.number_class(Decimal('-Infinity'))
4486 '-Infinity'
4487 >>> c.number_class(Decimal('NaN'))
4488 'NaN'
4489 >>> c.number_class(Decimal('-NaN'))
4490 'NaN'
4491 >>> c.number_class(Decimal('sNaN'))
4492 'sNaN'
4494 return a.number_class(context=self)
4496 def plus(self, a):
4497 """Plus corresponds to unary prefix plus in Python.
4499 The operation is evaluated using the same rules as add; the
4500 operation plus(a) is calculated as add('0', a) where the '0'
4501 has the same exponent as the operand.
4503 >>> ExtendedContext.plus(Decimal('1.3'))
4504 Decimal('1.3')
4505 >>> ExtendedContext.plus(Decimal('-1.3'))
4506 Decimal('-1.3')
4508 return a.__pos__(context=self)
4510 def power(self, a, b, modulo=None):
4511 """Raises a to the power of b, to modulo if given.
4513 With two arguments, compute a**b. If a is negative then b
4514 must be integral. The result will be inexact unless b is
4515 integral and the result is finite and can be expressed exactly
4516 in 'precision' digits.
4518 With three arguments, compute (a**b) % modulo. For the
4519 three argument form, the following restrictions on the
4520 arguments hold:
4522 - all three arguments must be integral
4523 - b must be nonnegative
4524 - at least one of a or b must be nonzero
4525 - modulo must be nonzero and have at most 'precision' digits
4527 The result of pow(a, b, modulo) is identical to the result
4528 that would be obtained by computing (a**b) % modulo with
4529 unbounded precision, but is computed more efficiently. It is
4530 always exact.
4532 >>> c = ExtendedContext.copy()
4533 >>> c.Emin = -999
4534 >>> c.Emax = 999
4535 >>> c.power(Decimal('2'), Decimal('3'))
4536 Decimal('8')
4537 >>> c.power(Decimal('-2'), Decimal('3'))
4538 Decimal('-8')
4539 >>> c.power(Decimal('2'), Decimal('-3'))
4540 Decimal('0.125')
4541 >>> c.power(Decimal('1.7'), Decimal('8'))
4542 Decimal('69.7575744')
4543 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4544 Decimal('2.00000000')
4545 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4546 Decimal('0')
4547 >>> c.power(Decimal('Infinity'), Decimal('0'))
4548 Decimal('1')
4549 >>> c.power(Decimal('Infinity'), Decimal('1'))
4550 Decimal('Infinity')
4551 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4552 Decimal('-0')
4553 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4554 Decimal('1')
4555 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4556 Decimal('-Infinity')
4557 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4558 Decimal('Infinity')
4559 >>> c.power(Decimal('0'), Decimal('0'))
4560 Decimal('NaN')
4562 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4563 Decimal('11')
4564 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4565 Decimal('-11')
4566 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4567 Decimal('1')
4568 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4569 Decimal('11')
4570 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4571 Decimal('11729830')
4572 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4573 Decimal('-0')
4574 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4575 Decimal('1')
4577 return a.__pow__(b, modulo, context=self)
4579 def quantize(self, a, b):
4580 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4582 The coefficient of the result is derived from that of the left-hand
4583 operand. It may be rounded using the current rounding setting (if the
4584 exponent is being increased), multiplied by a positive power of ten (if
4585 the exponent is being decreased), or is unchanged (if the exponent is
4586 already equal to that of the right-hand operand).
4588 Unlike other operations, if the length of the coefficient after the
4589 quantize operation would be greater than precision then an Invalid
4590 operation condition is raised. This guarantees that, unless there is
4591 an error condition, the exponent of the result of a quantize is always
4592 equal to that of the right-hand operand.
4594 Also unlike other operations, quantize will never raise Underflow, even
4595 if the result is subnormal and inexact.
4597 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4598 Decimal('2.170')
4599 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4600 Decimal('2.17')
4601 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4602 Decimal('2.2')
4603 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4604 Decimal('2')
4605 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4606 Decimal('0E+1')
4607 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4608 Decimal('-Infinity')
4609 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4610 Decimal('NaN')
4611 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4612 Decimal('-0')
4613 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4614 Decimal('-0E+5')
4615 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4616 Decimal('NaN')
4617 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4618 Decimal('NaN')
4619 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4620 Decimal('217.0')
4621 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4622 Decimal('217')
4623 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4624 Decimal('2.2E+2')
4625 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4626 Decimal('2E+2')
4628 return a.quantize(b, context=self)
4630 def radix(self):
4631 """Just returns 10, as this is Decimal, :)
4633 >>> ExtendedContext.radix()
4634 Decimal('10')
4636 return Decimal(10)
4638 def remainder(self, a, b):
4639 """Returns the remainder from integer division.
4641 The result is the residue of the dividend after the operation of
4642 calculating integer division as described for divide-integer, rounded
4643 to precision digits if necessary. The sign of the result, if
4644 non-zero, is the same as that of the original dividend.
4646 This operation will fail under the same conditions as integer division
4647 (that is, if integer division on the same two operands would fail, the
4648 remainder cannot be calculated).
4650 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4651 Decimal('2.1')
4652 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4653 Decimal('1')
4654 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4655 Decimal('-1')
4656 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4657 Decimal('0.2')
4658 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4659 Decimal('0.1')
4660 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4661 Decimal('1.0')
4663 return a.__mod__(b, context=self)
4665 def remainder_near(self, a, b):
4666 """Returns to be "a - b * n", where n is the integer nearest the exact
4667 value of "x / b" (if two integers are equally near then the even one
4668 is chosen). If the result is equal to 0 then its sign will be the
4669 sign of a.
4671 This operation will fail under the same conditions as integer division
4672 (that is, if integer division on the same two operands would fail, the
4673 remainder cannot be calculated).
4675 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4676 Decimal('-0.9')
4677 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4678 Decimal('-2')
4679 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4680 Decimal('1')
4681 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4682 Decimal('-1')
4683 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4684 Decimal('0.2')
4685 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4686 Decimal('0.1')
4687 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4688 Decimal('-0.3')
4690 return a.remainder_near(b, context=self)
4692 def rotate(self, a, b):
4693 """Returns a rotated copy of a, b times.
4695 The coefficient of the result is a rotated copy of the digits in
4696 the coefficient of the first operand. The number of places of
4697 rotation is taken from the absolute value of the second operand,
4698 with the rotation being to the left if the second operand is
4699 positive or to the right otherwise.
4701 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4702 Decimal('400000003')
4703 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4704 Decimal('12')
4705 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4706 Decimal('891234567')
4707 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4708 Decimal('123456789')
4709 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4710 Decimal('345678912')
4712 return a.rotate(b, context=self)
4714 def same_quantum(self, a, b):
4715 """Returns True if the two operands have the same exponent.
4717 The result is never affected by either the sign or the coefficient of
4718 either operand.
4720 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4721 False
4722 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4723 True
4724 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4725 False
4726 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4727 True
4729 return a.same_quantum(b)
4731 def scaleb (self, a, b):
4732 """Returns the first operand after adding the second value its exp.
4734 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4735 Decimal('0.0750')
4736 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4737 Decimal('7.50')
4738 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4739 Decimal('7.50E+3')
4741 return a.scaleb (b, context=self)
4743 def shift(self, a, b):
4744 """Returns a shifted copy of a, b times.
4746 The coefficient of the result is a shifted copy of the digits
4747 in the coefficient of the first operand. The number of places
4748 to shift is taken from the absolute value of the second operand,
4749 with the shift being to the left if the second operand is
4750 positive or to the right otherwise. Digits shifted into the
4751 coefficient are zeros.
4753 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4754 Decimal('400000000')
4755 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4756 Decimal('0')
4757 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4758 Decimal('1234567')
4759 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4760 Decimal('123456789')
4761 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4762 Decimal('345678900')
4764 return a.shift(b, context=self)
4766 def sqrt(self, a):
4767 """Square root of a non-negative number to context precision.
4769 If the result must be inexact, it is rounded using the round-half-even
4770 algorithm.
4772 >>> ExtendedContext.sqrt(Decimal('0'))
4773 Decimal('0')
4774 >>> ExtendedContext.sqrt(Decimal('-0'))
4775 Decimal('-0')
4776 >>> ExtendedContext.sqrt(Decimal('0.39'))
4777 Decimal('0.624499800')
4778 >>> ExtendedContext.sqrt(Decimal('100'))
4779 Decimal('10')
4780 >>> ExtendedContext.sqrt(Decimal('1'))
4781 Decimal('1')
4782 >>> ExtendedContext.sqrt(Decimal('1.0'))
4783 Decimal('1.0')
4784 >>> ExtendedContext.sqrt(Decimal('1.00'))
4785 Decimal('1.0')
4786 >>> ExtendedContext.sqrt(Decimal('7'))
4787 Decimal('2.64575131')
4788 >>> ExtendedContext.sqrt(Decimal('10'))
4789 Decimal('3.16227766')
4790 >>> ExtendedContext.prec
4793 return a.sqrt(context=self)
4795 def subtract(self, a, b):
4796 """Return the difference between the two operands.
4798 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4799 Decimal('0.23')
4800 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4801 Decimal('0.00')
4802 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4803 Decimal('-0.77')
4805 return a.__sub__(b, context=self)
4807 def to_eng_string(self, a):
4808 """Converts a number to a string, using scientific notation.
4810 The operation is not affected by the context.
4812 return a.to_eng_string(context=self)
4814 def to_sci_string(self, a):
4815 """Converts a number to a string, using scientific notation.
4817 The operation is not affected by the context.
4819 return a.__str__(context=self)
4821 def to_integral_exact(self, a):
4822 """Rounds to an integer.
4824 When the operand has a negative exponent, the result is the same
4825 as using the quantize() operation using the given operand as the
4826 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4827 of the operand as the precision setting; Inexact and Rounded flags
4828 are allowed in this operation. The rounding mode is taken from the
4829 context.
4831 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4832 Decimal('2')
4833 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4834 Decimal('100')
4835 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4836 Decimal('100')
4837 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4838 Decimal('102')
4839 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4840 Decimal('-102')
4841 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4842 Decimal('1.0E+6')
4843 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4844 Decimal('7.89E+77')
4845 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4846 Decimal('-Infinity')
4848 return a.to_integral_exact(context=self)
4850 def to_integral_value(self, a):
4851 """Rounds to an integer.
4853 When the operand has a negative exponent, the result is the same
4854 as using the quantize() operation using the given operand as the
4855 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4856 of the operand as the precision setting, except that no flags will
4857 be set. The rounding mode is taken from the context.
4859 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4860 Decimal('2')
4861 >>> ExtendedContext.to_integral_value(Decimal('100'))
4862 Decimal('100')
4863 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4864 Decimal('100')
4865 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4866 Decimal('102')
4867 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4868 Decimal('-102')
4869 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4870 Decimal('1.0E+6')
4871 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4872 Decimal('7.89E+77')
4873 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4874 Decimal('-Infinity')
4876 return a.to_integral_value(context=self)
4878 # the method name changed, but we provide also the old one, for compatibility
4879 to_integral = to_integral_value
4881 class _WorkRep(object):
4882 __slots__ = ('sign','int','exp')
4883 # sign: 0 or 1
4884 # int: int or long
4885 # exp: None, int, or string
4887 def __init__(self, value=None):
4888 if value is None:
4889 self.sign = None
4890 self.int = 0
4891 self.exp = None
4892 elif isinstance(value, Decimal):
4893 self.sign = value._sign
4894 self.int = int(value._int)
4895 self.exp = value._exp
4896 else:
4897 # assert isinstance(value, tuple)
4898 self.sign = value[0]
4899 self.int = value[1]
4900 self.exp = value[2]
4902 def __repr__(self):
4903 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4905 __str__ = __repr__
4909 def _normalize(op1, op2, prec = 0):
4910 """Normalizes op1, op2 to have the same exp and length of coefficient.
4912 Done during addition.
4914 if op1.exp < op2.exp:
4915 tmp = op2
4916 other = op1
4917 else:
4918 tmp = op1
4919 other = op2
4921 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4922 # Then adding 10**exp to tmp has the same effect (after rounding)
4923 # as adding any positive quantity smaller than 10**exp; similarly
4924 # for subtraction. So if other is smaller than 10**exp we replace
4925 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
4926 tmp_len = len(str(tmp.int))
4927 other_len = len(str(other.int))
4928 exp = tmp.exp + min(-1, tmp_len - prec - 2)
4929 if other_len + other.exp - 1 < exp:
4930 other.int = 1
4931 other.exp = exp
4933 tmp.int *= 10 ** (tmp.exp - other.exp)
4934 tmp.exp = other.exp
4935 return op1, op2
4937 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
4939 # This function from Tim Peters was taken from here:
4940 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
4941 # The correction being in the function definition is for speed, and
4942 # the whole function is not resolved with math.log because of avoiding
4943 # the use of floats.
4944 def _nbits(n, correction = {
4945 '0': 4, '1': 3, '2': 2, '3': 2,
4946 '4': 1, '5': 1, '6': 1, '7': 1,
4947 '8': 0, '9': 0, 'a': 0, 'b': 0,
4948 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
4949 """Number of bits in binary representation of the positive integer n,
4950 or 0 if n == 0.
4952 if n < 0:
4953 raise ValueError("The argument to _nbits should be nonnegative.")
4954 hex_n = "%x" % n
4955 return 4*len(hex_n) - correction[hex_n[0]]
4957 def _sqrt_nearest(n, a):
4958 """Closest integer to the square root of the positive integer n. a is
4959 an initial approximation to the square root. Any positive integer
4960 will do for a, but the closer a is to the square root of n the
4961 faster convergence will be.
4964 if n <= 0 or a <= 0:
4965 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
4968 while a != b:
4969 b, a = a, a--n//a>>1
4970 return a
4972 def _rshift_nearest(x, shift):
4973 """Given an integer x and a nonnegative integer shift, return closest
4974 integer to x / 2**shift; use round-to-even in case of a tie.
4977 b, q = 1L << shift, x >> shift
4978 return q + (2*(x & (b-1)) + (q&1) > b)
4980 def _div_nearest(a, b):
4981 """Closest integer to a/b, a and b positive integers; rounds to even
4982 in the case of a tie.
4985 q, r = divmod(a, b)
4986 return q + (2*r + (q&1) > b)
4988 def _ilog(x, M, L = 8):
4989 """Integer approximation to M*log(x/M), with absolute error boundable
4990 in terms only of x/M.
4992 Given positive integers x and M, return an integer approximation to
4993 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
4994 between the approximation and the exact result is at most 22. For
4995 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
4996 both cases these are upper bounds on the error; it will usually be
4997 much smaller."""
4999 # The basic algorithm is the following: let log1p be the function
5000 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5001 # the reduction
5003 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5005 # repeatedly until the argument to log1p is small (< 2**-L in
5006 # absolute value). For small y we can use the Taylor series
5007 # expansion
5009 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5011 # truncating at T such that y**T is small enough. The whole
5012 # computation is carried out in a form of fixed-point arithmetic,
5013 # with a real number z being represented by an integer
5014 # approximation to z*M. To avoid loss of precision, the y below
5015 # is actually an integer approximation to 2**R*y*M, where R is the
5016 # number of reductions performed so far.
5018 y = x-M
5019 # argument reduction; R = number of reductions performed
5020 R = 0
5021 while (R <= L and long(abs(y)) << L-R >= M or
5022 R > L and abs(y) >> R-L >= M):
5023 y = _div_nearest(long(M*y) << 1,
5024 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5025 R += 1
5027 # Taylor series with T terms
5028 T = -int(-10*len(str(M))//(3*L))
5029 yshift = _rshift_nearest(y, R)
5030 w = _div_nearest(M, T)
5031 for k in xrange(T-1, 0, -1):
5032 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5034 return _div_nearest(w*y, M)
5036 def _dlog10(c, e, p):
5037 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5038 approximation to 10**p * log10(c*10**e), with an absolute error of
5039 at most 1. Assumes that c*10**e is not exactly 1."""
5041 # increase precision by 2; compensate for this by dividing
5042 # final result by 100
5043 p += 2
5045 # write c*10**e as d*10**f with either:
5046 # f >= 0 and 1 <= d <= 10, or
5047 # f <= 0 and 0.1 <= d <= 1.
5048 # Thus for c*10**e close to 1, f = 0
5049 l = len(str(c))
5050 f = e+l - (e+l >= 1)
5052 if p > 0:
5053 M = 10**p
5054 k = e+p-f
5055 if k >= 0:
5056 c *= 10**k
5057 else:
5058 c = _div_nearest(c, 10**-k)
5060 log_d = _ilog(c, M) # error < 5 + 22 = 27
5061 log_10 = _log10_digits(p) # error < 1
5062 log_d = _div_nearest(log_d*M, log_10)
5063 log_tenpower = f*M # exact
5064 else:
5065 log_d = 0 # error < 2.31
5066 log_tenpower = div_nearest(f, 10**-p) # error < 0.5
5068 return _div_nearest(log_tenpower+log_d, 100)
5070 def _dlog(c, e, p):
5071 """Given integers c, e and p with c > 0, compute an integer
5072 approximation to 10**p * log(c*10**e), with an absolute error of
5073 at most 1. Assumes that c*10**e is not exactly 1."""
5075 # Increase precision by 2. The precision increase is compensated
5076 # for at the end with a division by 100.
5077 p += 2
5079 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5080 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5081 # as 10**p * log(d) + 10**p*f * log(10).
5082 l = len(str(c))
5083 f = e+l - (e+l >= 1)
5085 # compute approximation to 10**p*log(d), with error < 27
5086 if p > 0:
5087 k = e+p-f
5088 if k >= 0:
5089 c *= 10**k
5090 else:
5091 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5093 # _ilog magnifies existing error in c by a factor of at most 10
5094 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5095 else:
5096 # p <= 0: just approximate the whole thing by 0; error < 2.31
5097 log_d = 0
5099 # compute approximation to f*10**p*log(10), with error < 11.
5100 if f:
5101 extra = len(str(abs(f)))-1
5102 if p + extra >= 0:
5103 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5104 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5105 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5106 else:
5107 f_log_ten = 0
5108 else:
5109 f_log_ten = 0
5111 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5112 return _div_nearest(f_log_ten + log_d, 100)
5114 class _Log10Memoize(object):
5115 """Class to compute, store, and allow retrieval of, digits of the
5116 constant log(10) = 2.302585.... This constant is needed by
5117 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5118 def __init__(self):
5119 self.digits = "23025850929940456840179914546843642076011014886"
5121 def getdigits(self, p):
5122 """Given an integer p >= 0, return floor(10**p)*log(10).
5124 For example, self.getdigits(3) returns 2302.
5126 # digits are stored as a string, for quick conversion to
5127 # integer in the case that we've already computed enough
5128 # digits; the stored digits should always be correct
5129 # (truncated, not rounded to nearest).
5130 if p < 0:
5131 raise ValueError("p should be nonnegative")
5133 if p >= len(self.digits):
5134 # compute p+3, p+6, p+9, ... digits; continue until at
5135 # least one of the extra digits is nonzero
5136 extra = 3
5137 while True:
5138 # compute p+extra digits, correct to within 1ulp
5139 M = 10**(p+extra+2)
5140 digits = str(_div_nearest(_ilog(10*M, M), 100))
5141 if digits[-extra:] != '0'*extra:
5142 break
5143 extra += 3
5144 # keep all reliable digits so far; remove trailing zeros
5145 # and next nonzero digit
5146 self.digits = digits.rstrip('0')[:-1]
5147 return int(self.digits[:p+1])
5149 _log10_digits = _Log10Memoize().getdigits
5151 def _iexp(x, M, L=8):
5152 """Given integers x and M, M > 0, such that x/M is small in absolute
5153 value, compute an integer approximation to M*exp(x/M). For 0 <=
5154 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5155 is usually much smaller)."""
5157 # Algorithm: to compute exp(z) for a real number z, first divide z
5158 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5159 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5160 # series
5162 # expm1(x) = x + x**2/2! + x**3/3! + ...
5164 # Now use the identity
5166 # expm1(2x) = expm1(x)*(expm1(x)+2)
5168 # R times to compute the sequence expm1(z/2**R),
5169 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5171 # Find R such that x/2**R/M <= 2**-L
5172 R = _nbits((long(x)<<L)//M)
5174 # Taylor series. (2**L)**T > M
5175 T = -int(-10*len(str(M))//(3*L))
5176 y = _div_nearest(x, T)
5177 Mshift = long(M)<<R
5178 for i in xrange(T-1, 0, -1):
5179 y = _div_nearest(x*(Mshift + y), Mshift * i)
5181 # Expansion
5182 for k in xrange(R-1, -1, -1):
5183 Mshift = long(M)<<(k+2)
5184 y = _div_nearest(y*(y+Mshift), Mshift)
5186 return M+y
5188 def _dexp(c, e, p):
5189 """Compute an approximation to exp(c*10**e), with p decimal places of
5190 precision.
5192 Returns integers d, f such that:
5194 10**(p-1) <= d <= 10**p, and
5195 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5197 In other words, d*10**f is an approximation to exp(c*10**e) with p
5198 digits of precision, and with an error in d of at most 1. This is
5199 almost, but not quite, the same as the error being < 1ulp: when d
5200 = 10**(p-1) the error could be up to 10 ulp."""
5202 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5203 p += 2
5205 # compute log(10) with extra precision = adjusted exponent of c*10**e
5206 extra = max(0, e + len(str(c)) - 1)
5207 q = p + extra
5209 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5210 # rounding down
5211 shift = e+q
5212 if shift >= 0:
5213 cshift = c*10**shift
5214 else:
5215 cshift = c//10**-shift
5216 quot, rem = divmod(cshift, _log10_digits(q))
5218 # reduce remainder back to original precision
5219 rem = _div_nearest(rem, 10**extra)
5221 # error in result of _iexp < 120; error after division < 0.62
5222 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5224 def _dpower(xc, xe, yc, ye, p):
5225 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5226 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5228 10**(p-1) <= c <= 10**p, and
5229 (c-1)*10**e < x**y < (c+1)*10**e
5231 in other words, c*10**e is an approximation to x**y with p digits
5232 of precision, and with an error in c of at most 1. (This is
5233 almost, but not quite, the same as the error being < 1ulp: when c
5234 == 10**(p-1) we can only guarantee error < 10ulp.)
5236 We assume that: x is positive and not equal to 1, and y is nonzero.
5239 # Find b such that 10**(b-1) <= |y| <= 10**b
5240 b = len(str(abs(yc))) + ye
5242 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5243 lxc = _dlog(xc, xe, p+b+1)
5245 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5246 shift = ye-b
5247 if shift >= 0:
5248 pc = lxc*yc*10**shift
5249 else:
5250 pc = _div_nearest(lxc*yc, 10**-shift)
5252 if pc == 0:
5253 # we prefer a result that isn't exactly 1; this makes it
5254 # easier to compute a correctly rounded result in __pow__
5255 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5256 coeff, exp = 10**(p-1)+1, 1-p
5257 else:
5258 coeff, exp = 10**p-1, -p
5259 else:
5260 coeff, exp = _dexp(pc, -(p+1), p+1)
5261 coeff = _div_nearest(coeff, 10)
5262 exp += 1
5264 return coeff, exp
5266 def _log10_lb(c, correction = {
5267 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5268 '6': 23, '7': 16, '8': 10, '9': 5}):
5269 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5270 if c <= 0:
5271 raise ValueError("The argument to _log10_lb should be nonnegative.")
5272 str_c = str(c)
5273 return 100*len(str_c) - correction[str_c[0]]
5275 ##### Helper Functions ####################################################
5277 def _convert_other(other, raiseit=False):
5278 """Convert other to Decimal.
5280 Verifies that it's ok to use in an implicit construction.
5282 if isinstance(other, Decimal):
5283 return other
5284 if isinstance(other, (int, long)):
5285 return Decimal(other)
5286 if raiseit:
5287 raise TypeError("Unable to convert %s to Decimal" % other)
5288 return NotImplemented
5290 ##### Setup Specific Contexts ############################################
5292 # The default context prototype used by Context()
5293 # Is mutable, so that new contexts can have different default values
5295 DefaultContext = Context(
5296 prec=28, rounding=ROUND_HALF_EVEN,
5297 traps=[DivisionByZero, Overflow, InvalidOperation],
5298 flags=[],
5299 Emax=999999999,
5300 Emin=-999999999,
5301 capitals=1
5304 # Pre-made alternate contexts offered by the specification
5305 # Don't change these; the user should be able to select these
5306 # contexts and be able to reproduce results from other implementations
5307 # of the spec.
5309 BasicContext = Context(
5310 prec=9, rounding=ROUND_HALF_UP,
5311 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5312 flags=[],
5315 ExtendedContext = Context(
5316 prec=9, rounding=ROUND_HALF_EVEN,
5317 traps=[],
5318 flags=[],
5322 ##### crud for parsing strings #############################################
5324 # Regular expression used for parsing numeric strings. Additional
5325 # comments:
5327 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5328 # whitespace. But note that the specification disallows whitespace in
5329 # a numeric string.
5331 # 2. For finite numbers (not infinities and NaNs) the body of the
5332 # number between the optional sign and the optional exponent must have
5333 # at least one decimal digit, possibly after the decimal point. The
5334 # lookahead expression '(?=\d|\.\d)' checks this.
5336 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5337 # other meaning for \d than the numbers [0-9].
5339 import re
5340 _parser = re.compile(r""" # A numeric string consists of:
5341 # \s*
5342 (?P<sign>[-+])? # an optional sign, followed by either...
5344 (?=\d|\.\d) # ...a number (with at least one digit)
5345 (?P<int>\d*) # consisting of a (possibly empty) integer part
5346 (\.(?P<frac>\d*))? # followed by an optional fractional part
5347 (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or...
5349 Inf(inity)? # ...an infinity, or...
5351 (?P<signal>s)? # ...an (optionally signaling)
5352 NaN # NaN
5353 (?P<diag>\d*) # with (possibly empty) diagnostic information.
5355 # \s*
5357 """, re.VERBOSE | re.IGNORECASE).match
5359 _all_zeros = re.compile('0*$').match
5360 _exact_half = re.compile('50*$').match
5362 ##### PEP3101 support functions ##############################################
5363 # The functions parse_format_specifier and format_align have little to do
5364 # with the Decimal class, and could potentially be reused for other pure
5365 # Python numeric classes that want to implement __format__
5367 # A format specifier for Decimal looks like:
5369 # [[fill]align][sign][0][minimumwidth][.precision][type]
5372 _parse_format_specifier_regex = re.compile(r"""\A
5374 (?P<fill>.)?
5375 (?P<align>[<>=^])
5377 (?P<sign>[-+ ])?
5378 (?P<zeropad>0)?
5379 (?P<minimumwidth>(?!0)\d+)?
5380 (?:\.(?P<precision>0|(?!0)\d+))?
5381 (?P<type>[eEfFgG%])?
5383 """, re.VERBOSE)
5385 del re
5387 def _parse_format_specifier(format_spec):
5388 """Parse and validate a format specifier.
5390 Turns a standard numeric format specifier into a dict, with the
5391 following entries:
5393 fill: fill character to pad field to minimum width
5394 align: alignment type, either '<', '>', '=' or '^'
5395 sign: either '+', '-' or ' '
5396 minimumwidth: nonnegative integer giving minimum width
5397 precision: nonnegative integer giving precision, or None
5398 type: one of the characters 'eEfFgG%', or None
5399 unicode: either True or False (always True for Python 3.x)
5402 m = _parse_format_specifier_regex.match(format_spec)
5403 if m is None:
5404 raise ValueError("Invalid format specifier: " + format_spec)
5406 # get the dictionary
5407 format_dict = m.groupdict()
5409 # defaults for fill and alignment
5410 fill = format_dict['fill']
5411 align = format_dict['align']
5412 if format_dict.pop('zeropad') is not None:
5413 # in the face of conflict, refuse the temptation to guess
5414 if fill is not None and fill != '0':
5415 raise ValueError("Fill character conflicts with '0'"
5416 " in format specifier: " + format_spec)
5417 if align is not None and align != '=':
5418 raise ValueError("Alignment conflicts with '0' in "
5419 "format specifier: " + format_spec)
5420 fill = '0'
5421 align = '='
5422 format_dict['fill'] = fill or ' '
5423 format_dict['align'] = align or '<'
5425 if format_dict['sign'] is None:
5426 format_dict['sign'] = '-'
5428 # turn minimumwidth and precision entries into integers.
5429 # minimumwidth defaults to 0; precision remains None if not given
5430 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5431 if format_dict['precision'] is not None:
5432 format_dict['precision'] = int(format_dict['precision'])
5434 # if format type is 'g' or 'G' then a precision of 0 makes little
5435 # sense; convert it to 1. Same if format type is unspecified.
5436 if format_dict['precision'] == 0:
5437 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5438 format_dict['precision'] = 1
5440 # record whether return type should be str or unicode
5441 format_dict['unicode'] = isinstance(format_spec, unicode)
5443 return format_dict
5445 def _format_align(body, spec_dict):
5446 """Given an unpadded, non-aligned numeric string, add padding and
5447 aligment to conform with the given format specifier dictionary (as
5448 output from parse_format_specifier).
5450 It's assumed that if body is negative then it starts with '-'.
5451 Any leading sign ('-' or '+') is stripped from the body before
5452 applying the alignment and padding rules, and replaced in the
5453 appropriate position.
5456 # figure out the sign; we only examine the first character, so if
5457 # body has leading whitespace the results may be surprising.
5458 if len(body) > 0 and body[0] in '-+':
5459 sign = body[0]
5460 body = body[1:]
5461 else:
5462 sign = ''
5464 if sign != '-':
5465 if spec_dict['sign'] in ' +':
5466 sign = spec_dict['sign']
5467 else:
5468 sign = ''
5470 # how much extra space do we have to play with?
5471 minimumwidth = spec_dict['minimumwidth']
5472 fill = spec_dict['fill']
5473 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5475 align = spec_dict['align']
5476 if align == '<':
5477 result = padding + sign + body
5478 elif align == '>':
5479 result = sign + body + padding
5480 elif align == '=':
5481 result = sign + padding + body
5482 else: #align == '^'
5483 half = len(padding)//2
5484 result = padding[:half] + sign + body + padding[half:]
5486 # make sure that result is unicode if necessary
5487 if spec_dict['unicode']:
5488 result = unicode(result)
5490 return result
5492 ##### Useful Constants (internal use only) ################################
5494 # Reusable defaults
5495 Inf = Decimal('Inf')
5496 negInf = Decimal('-Inf')
5497 NaN = Decimal('NaN')
5498 Dec_0 = Decimal(0)
5499 Dec_p1 = Decimal(1)
5500 Dec_n1 = Decimal(-1)
5502 # Infsign[sign] is infinity w/ that sign
5503 Infsign = (Inf, negInf)
5507 if __name__ == '__main__':
5508 import doctest, sys
5509 doctest.testmod(sys.modules[__name__])