Make importlib backwards-compatible to Python 2.2 (but this is not promised to
[python.git] / Lib / decimal.py
blobdfc7043dde0f0de80e0c2882424685446038854d
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
138 import math as _math
139 import numbers as _numbers
141 try:
142 from collections import namedtuple as _namedtuple
143 DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
144 except ImportError:
145 DecimalTuple = lambda *args: args
147 # Rounding
148 ROUND_DOWN = 'ROUND_DOWN'
149 ROUND_HALF_UP = 'ROUND_HALF_UP'
150 ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
151 ROUND_CEILING = 'ROUND_CEILING'
152 ROUND_FLOOR = 'ROUND_FLOOR'
153 ROUND_UP = 'ROUND_UP'
154 ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
155 ROUND_05UP = 'ROUND_05UP'
157 # Errors
159 class DecimalException(ArithmeticError):
160 """Base exception class.
162 Used exceptions derive from this.
163 If an exception derives from another exception besides this (such as
164 Underflow (Inexact, Rounded, Subnormal) that indicates that it is only
165 called if the others are present. This isn't actually used for
166 anything, though.
168 handle -- Called when context._raise_error is called and the
169 trap_enabler is set. First argument is self, second is the
170 context. More arguments can be given, those being after
171 the explanation in _raise_error (For example,
172 context._raise_error(NewError, '(-x)!', self._sign) would
173 call NewError().handle(context, self._sign).)
175 To define a new exception, it should be sufficient to have it derive
176 from DecimalException.
178 def handle(self, context, *args):
179 pass
182 class Clamped(DecimalException):
183 """Exponent of a 0 changed to fit bounds.
185 This occurs and signals clamped if the exponent of a result has been
186 altered in order to fit the constraints of a specific concrete
187 representation. This may occur when the exponent of a zero result would
188 be outside the bounds of a representation, or when a large normal
189 number would have an encoded exponent that cannot be represented. In
190 this latter case, the exponent is reduced to fit and the corresponding
191 number of zero digits are appended to the coefficient ("fold-down").
194 class InvalidOperation(DecimalException):
195 """An invalid operation was performed.
197 Various bad things cause this:
199 Something creates a signaling NaN
200 -INF + INF
201 0 * (+-)INF
202 (+-)INF / (+-)INF
203 x % 0
204 (+-)INF % x
205 x._rescale( non-integer )
206 sqrt(-x) , x > 0
207 0 ** 0
208 x ** (non-integer)
209 x ** (+-)INF
210 An operand is invalid
212 The result of the operation after these is a quiet positive NaN,
213 except when the cause is a signaling NaN, in which case the result is
214 also a quiet NaN, but with the original sign, and an optional
215 diagnostic information.
217 def handle(self, context, *args):
218 if args:
219 ans = _dec_from_triple(args[0]._sign, args[0]._int, 'n', True)
220 return ans._fix_nan(context)
221 return _NaN
223 class ConversionSyntax(InvalidOperation):
224 """Trying to convert badly formed string.
226 This occurs and signals invalid-operation if an string is being
227 converted to a number and it does not conform to the numeric string
228 syntax. The result is [0,qNaN].
230 def handle(self, context, *args):
231 return _NaN
233 class DivisionByZero(DecimalException, ZeroDivisionError):
234 """Division by 0.
236 This occurs and signals division-by-zero if division of a finite number
237 by zero was attempted (during a divide-integer or divide operation, or a
238 power operation with negative right-hand operand), and the dividend was
239 not zero.
241 The result of the operation is [sign,inf], where sign is the exclusive
242 or of the signs of the operands for divide, or is 1 for an odd power of
243 -0, for power.
246 def handle(self, context, sign, *args):
247 return _SignedInfinity[sign]
249 class DivisionImpossible(InvalidOperation):
250 """Cannot perform the division adequately.
252 This occurs and signals invalid-operation if the integer result of a
253 divide-integer or remainder operation had too many digits (would be
254 longer than precision). The result is [0,qNaN].
257 def handle(self, context, *args):
258 return _NaN
260 class DivisionUndefined(InvalidOperation, ZeroDivisionError):
261 """Undefined result of division.
263 This occurs and signals invalid-operation if division by zero was
264 attempted (during a divide-integer, divide, or remainder operation), and
265 the dividend is also zero. The result is [0,qNaN].
268 def handle(self, context, *args):
269 return _NaN
271 class Inexact(DecimalException):
272 """Had to round, losing information.
274 This occurs and signals inexact whenever the result of an operation is
275 not exact (that is, it needed to be rounded and any discarded digits
276 were non-zero), or if an overflow or underflow condition occurs. The
277 result in all cases is unchanged.
279 The inexact signal may be tested (or trapped) to determine if a given
280 operation (or sequence of operations) was inexact.
283 class InvalidContext(InvalidOperation):
284 """Invalid context. Unknown rounding, for example.
286 This occurs and signals invalid-operation if an invalid context was
287 detected during an operation. This can occur if contexts are not checked
288 on creation and either the precision exceeds the capability of the
289 underlying concrete representation or an unknown or unsupported rounding
290 was specified. These aspects of the context need only be checked when
291 the values are required to be used. The result is [0,qNaN].
294 def handle(self, context, *args):
295 return _NaN
297 class Rounded(DecimalException):
298 """Number got rounded (not necessarily changed during rounding).
300 This occurs and signals rounded whenever the result of an operation is
301 rounded (that is, some zero or non-zero digits were discarded from the
302 coefficient), or if an overflow or underflow condition occurs. The
303 result in all cases is unchanged.
305 The rounded signal may be tested (or trapped) to determine if a given
306 operation (or sequence of operations) caused a loss of precision.
309 class Subnormal(DecimalException):
310 """Exponent < Emin before rounding.
312 This occurs and signals subnormal whenever the result of a conversion or
313 operation is subnormal (that is, its adjusted exponent is less than
314 Emin, before any rounding). The result in all cases is unchanged.
316 The subnormal signal may be tested (or trapped) to determine if a given
317 or operation (or sequence of operations) yielded a subnormal result.
320 class Overflow(Inexact, Rounded):
321 """Numerical overflow.
323 This occurs and signals overflow if the adjusted exponent of a result
324 (from a conversion or from an operation that is not an attempt to divide
325 by zero), after rounding, would be greater than the largest value that
326 can be handled by the implementation (the value Emax).
328 The result depends on the rounding mode:
330 For round-half-up and round-half-even (and for round-half-down and
331 round-up, if implemented), the result of the operation is [sign,inf],
332 where sign is the sign of the intermediate result. For round-down, the
333 result is the largest finite number that can be represented in the
334 current precision, with the sign of the intermediate result. For
335 round-ceiling, the result is the same as for round-down if the sign of
336 the intermediate result is 1, or is [0,inf] otherwise. For round-floor,
337 the result is the same as for round-down if the sign of the intermediate
338 result is 0, or is [1,inf] otherwise. In all cases, Inexact and Rounded
339 will also be raised.
342 def handle(self, context, sign, *args):
343 if context.rounding in (ROUND_HALF_UP, ROUND_HALF_EVEN,
344 ROUND_HALF_DOWN, ROUND_UP):
345 return _SignedInfinity[sign]
346 if sign == 0:
347 if context.rounding == ROUND_CEILING:
348 return _SignedInfinity[sign]
349 return _dec_from_triple(sign, '9'*context.prec,
350 context.Emax-context.prec+1)
351 if sign == 1:
352 if context.rounding == ROUND_FLOOR:
353 return _SignedInfinity[sign]
354 return _dec_from_triple(sign, '9'*context.prec,
355 context.Emax-context.prec+1)
358 class Underflow(Inexact, Rounded, Subnormal):
359 """Numerical underflow with result rounded to 0.
361 This occurs and signals underflow if a result is inexact and the
362 adjusted exponent of the result would be smaller (more negative) than
363 the smallest value that can be handled by the implementation (the value
364 Emin). That is, the result is both inexact and subnormal.
366 The result after an underflow will be a subnormal number rounded, if
367 necessary, so that its exponent is not less than Etiny. This may result
368 in 0 with the sign of the intermediate result and an exponent of Etiny.
370 In all cases, Inexact, Rounded, and Subnormal will also be raised.
373 # List of public traps and flags
374 _signals = [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
375 Underflow, InvalidOperation, Subnormal]
377 # Map conditions (per the spec) to signals
378 _condition_map = {ConversionSyntax:InvalidOperation,
379 DivisionImpossible:InvalidOperation,
380 DivisionUndefined:InvalidOperation,
381 InvalidContext:InvalidOperation}
383 ##### Context Functions ##################################################
385 # The getcontext() and setcontext() function manage access to a thread-local
386 # current context. Py2.4 offers direct support for thread locals. If that
387 # is not available, use threading.currentThread() which is slower but will
388 # work for older Pythons. If threads are not part of the build, create a
389 # mock threading object with threading.local() returning the module namespace.
391 try:
392 import threading
393 except ImportError:
394 # Python was compiled without threads; create a mock object instead
395 import sys
396 class MockThreading(object):
397 def local(self, sys=sys):
398 return sys.modules[__name__]
399 threading = MockThreading()
400 del sys, MockThreading
402 try:
403 threading.local
405 except AttributeError:
407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
409 if hasattr(threading.currentThread(), '__decimal_context__'):
410 del threading.currentThread().__decimal_context__
412 def setcontext(context):
413 """Set this thread's context to context."""
414 if context in (DefaultContext, BasicContext, ExtendedContext):
415 context = context.copy()
416 context.clear_flags()
417 threading.currentThread().__decimal_context__ = context
419 def getcontext():
420 """Returns this thread's context.
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
426 try:
427 return threading.currentThread().__decimal_context__
428 except AttributeError:
429 context = Context()
430 threading.currentThread().__decimal_context__ = context
431 return context
433 else:
435 local = threading.local()
436 if hasattr(local, '__decimal_context__'):
437 del local.__decimal_context__
439 def getcontext(_local=local):
440 """Returns this thread's context.
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
446 try:
447 return _local.__decimal_context__
448 except AttributeError:
449 context = Context()
450 _local.__decimal_context__ = context
451 return context
453 def setcontext(context, _local=local):
454 """Set this thread's context to context."""
455 if context in (DefaultContext, BasicContext, ExtendedContext):
456 context = context.copy()
457 context.clear_flags()
458 _local.__decimal_context__ = context
460 del threading, local # Don't contaminate the namespace
462 def localcontext(ctx=None):
463 """Return a context manager for a copy of the supplied context
465 Uses a copy of the current context if no context is specified
466 The returned context manager creates a local decimal context
467 in a with statement:
468 def sin(x):
469 with localcontext() as ctx:
470 ctx.prec += 2
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
473 return +s # Convert result to normal precision
475 def sin(x):
476 with localcontext(ExtendedContext):
477 # Rest of sin calculation algorithm
478 # uses the Extended Context from the
479 # General Decimal Arithmetic Specification
480 return +s # Convert result to normal context
482 >>> setcontext(DefaultContext)
483 >>> print getcontext().prec
485 >>> with localcontext():
486 ... ctx = getcontext()
487 ... ctx.prec += 2
488 ... print ctx.prec
491 >>> with localcontext(ExtendedContext):
492 ... print getcontext().prec
495 >>> print getcontext().prec
498 if ctx is None: ctx = getcontext()
499 return _ContextManager(ctx)
502 ##### Decimal class #######################################################
504 class Decimal(object):
505 """Floating point class for decimal arithmetic."""
507 __slots__ = ('_exp','_int','_sign', '_is_special')
508 # Generally, the value of the Decimal instance is given by
509 # (-1)**_sign * _int * 10**_exp
510 # Special values are signified by _is_special == True
512 # We're immutable, so use __new__ not __init__
513 def __new__(cls, value="0", context=None):
514 """Create a decimal point instance.
516 >>> Decimal('3.14') # string input
517 Decimal('3.14')
518 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
519 Decimal('3.14')
520 >>> Decimal(314) # int or long
521 Decimal('314')
522 >>> Decimal(Decimal(314)) # another decimal instance
523 Decimal('314')
524 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
525 Decimal('3.14')
528 # Note that the coefficient, self._int, is actually stored as
529 # a string rather than as a tuple of digits. This speeds up
530 # the "digits to integer" and "integer to digits" conversions
531 # that are used in almost every arithmetic operation on
532 # Decimals. This is an internal detail: the as_tuple function
533 # and the Decimal constructor still deal with tuples of
534 # digits.
536 self = object.__new__(cls)
538 # From a string
539 # REs insist on real strings, so we can too.
540 if isinstance(value, basestring):
541 m = _parser(value.strip())
542 if m is None:
543 if context is None:
544 context = getcontext()
545 return context._raise_error(ConversionSyntax,
546 "Invalid literal for Decimal: %r" % value)
548 if m.group('sign') == "-":
549 self._sign = 1
550 else:
551 self._sign = 0
552 intpart = m.group('int')
553 if intpart is not None:
554 # finite number
555 fracpart = m.group('frac')
556 exp = int(m.group('exp') or '0')
557 if fracpart is not None:
558 self._int = str((intpart+fracpart).lstrip('0') or '0')
559 self._exp = exp - len(fracpart)
560 else:
561 self._int = str(intpart.lstrip('0') or '0')
562 self._exp = exp
563 self._is_special = False
564 else:
565 diag = m.group('diag')
566 if diag is not None:
567 # NaN
568 self._int = str(diag.lstrip('0'))
569 if m.group('signal'):
570 self._exp = 'N'
571 else:
572 self._exp = 'n'
573 else:
574 # infinity
575 self._int = '0'
576 self._exp = 'F'
577 self._is_special = True
578 return self
580 # From an integer
581 if isinstance(value, (int,long)):
582 if value >= 0:
583 self._sign = 0
584 else:
585 self._sign = 1
586 self._exp = 0
587 self._int = str(abs(value))
588 self._is_special = False
589 return self
591 # From another decimal
592 if isinstance(value, Decimal):
593 self._exp = value._exp
594 self._sign = value._sign
595 self._int = value._int
596 self._is_special = value._is_special
597 return self
599 # From an internal working value
600 if isinstance(value, _WorkRep):
601 self._sign = value.sign
602 self._int = str(value.int)
603 self._exp = int(value.exp)
604 self._is_special = False
605 return self
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value, (list,tuple)):
609 if len(value) != 3:
610 raise ValueError('Invalid tuple size in creation of Decimal '
611 'from list or tuple. The list or tuple '
612 'should have exactly three elements.')
613 # process sign. The isinstance test rejects floats
614 if not (isinstance(value[0], (int, long)) and value[0] in (0,1)):
615 raise ValueError("Invalid sign. The first value in the tuple "
616 "should be an integer; either 0 for a "
617 "positive number or 1 for a negative number.")
618 self._sign = value[0]
619 if value[2] == 'F':
620 # infinity: value[1] is ignored
621 self._int = '0'
622 self._exp = value[2]
623 self._is_special = True
624 else:
625 # process and validate the digits in value[1]
626 digits = []
627 for digit in value[1]:
628 if isinstance(digit, (int, long)) and 0 <= digit <= 9:
629 # skip leading zeros
630 if digits or digit != 0:
631 digits.append(digit)
632 else:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
635 "0 through 9.")
636 if value[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
638 self._int = ''.join(map(str, digits))
639 self._exp = value[2]
640 self._is_special = True
641 elif isinstance(value[2], (int, long)):
642 # finite number: digits give the coefficient
643 self._int = ''.join(map(str, digits or [0]))
644 self._exp = value[2]
645 self._is_special = False
646 else:
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
650 return self
652 if isinstance(value, float):
653 raise TypeError("Cannot convert float to Decimal. " +
654 "First convert the float to a string")
656 raise TypeError("Cannot convert %r to Decimal" % value)
658 # @classmethod, but @decorator is not valid Python 2.3 syntax, so
659 # don't use it (see notes on Py2.3 compatibility at top of file)
660 def from_float(cls, f):
661 """Converts a float to a decimal number, exactly.
663 Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
664 Since 0.1 is not exactly representable in binary floating point, the
665 value is stored as the nearest representable value which is
666 0x1.999999999999ap-4. The exact equivalent of the value in decimal
667 is 0.1000000000000000055511151231257827021181583404541015625.
669 >>> Decimal.from_float(0.1)
670 Decimal('0.1000000000000000055511151231257827021181583404541015625')
671 >>> Decimal.from_float(float('nan'))
672 Decimal('NaN')
673 >>> Decimal.from_float(float('inf'))
674 Decimal('Infinity')
675 >>> Decimal.from_float(-float('inf'))
676 Decimal('-Infinity')
677 >>> Decimal.from_float(-0.0)
678 Decimal('-0')
681 if isinstance(f, (int, long)): # handle integer inputs
682 return cls(f)
683 if _math.isinf(f) or _math.isnan(f): # raises TypeError if not a float
684 return cls(repr(f))
685 if _math.copysign(1.0, f) == 1.0:
686 sign = 0
687 else:
688 sign = 1
689 n, d = abs(f).as_integer_ratio()
690 k = d.bit_length() - 1
691 result = _dec_from_triple(sign, str(n*5**k), -k)
692 if cls is Decimal:
693 return result
694 else:
695 return cls(result)
696 from_float = classmethod(from_float)
698 def _isnan(self):
699 """Returns whether the number is not actually one.
701 0 if a number
702 1 if NaN
703 2 if sNaN
705 if self._is_special:
706 exp = self._exp
707 if exp == 'n':
708 return 1
709 elif exp == 'N':
710 return 2
711 return 0
713 def _isinfinity(self):
714 """Returns whether the number is infinite
716 0 if finite or not a number
717 1 if +INF
718 -1 if -INF
720 if self._exp == 'F':
721 if self._sign:
722 return -1
723 return 1
724 return 0
726 def _check_nans(self, other=None, context=None):
727 """Returns whether the number is not actually one.
729 if self, other are sNaN, signal
730 if self, other are NaN return nan
731 return 0
733 Done before operations.
736 self_is_nan = self._isnan()
737 if other is None:
738 other_is_nan = False
739 else:
740 other_is_nan = other._isnan()
742 if self_is_nan or other_is_nan:
743 if context is None:
744 context = getcontext()
746 if self_is_nan == 2:
747 return context._raise_error(InvalidOperation, 'sNaN',
748 self)
749 if other_is_nan == 2:
750 return context._raise_error(InvalidOperation, 'sNaN',
751 other)
752 if self_is_nan:
753 return self._fix_nan(context)
755 return other._fix_nan(context)
756 return 0
758 def _compare_check_nans(self, other, context):
759 """Version of _check_nans used for the signaling comparisons
760 compare_signal, __le__, __lt__, __ge__, __gt__.
762 Signal InvalidOperation if either self or other is a (quiet
763 or signaling) NaN. Signaling NaNs take precedence over quiet
764 NaNs.
766 Return 0 if neither operand is a NaN.
769 if context is None:
770 context = getcontext()
772 if self._is_special or other._is_special:
773 if self.is_snan():
774 return context._raise_error(InvalidOperation,
775 'comparison involving sNaN',
776 self)
777 elif other.is_snan():
778 return context._raise_error(InvalidOperation,
779 'comparison involving sNaN',
780 other)
781 elif self.is_qnan():
782 return context._raise_error(InvalidOperation,
783 'comparison involving NaN',
784 self)
785 elif other.is_qnan():
786 return context._raise_error(InvalidOperation,
787 'comparison involving NaN',
788 other)
789 return 0
791 def __nonzero__(self):
792 """Return True if self is nonzero; otherwise return False.
794 NaNs and infinities are considered nonzero.
796 return self._is_special or self._int != '0'
798 def _cmp(self, other):
799 """Compare the two non-NaN decimal instances self and other.
801 Returns -1 if self < other, 0 if self == other and 1
802 if self > other. This routine is for internal use only."""
804 if self._is_special or other._is_special:
805 self_inf = self._isinfinity()
806 other_inf = other._isinfinity()
807 if self_inf == other_inf:
808 return 0
809 elif self_inf < other_inf:
810 return -1
811 else:
812 return 1
814 # check for zeros; Decimal('0') == Decimal('-0')
815 if not self:
816 if not other:
817 return 0
818 else:
819 return -((-1)**other._sign)
820 if not other:
821 return (-1)**self._sign
823 # If different signs, neg one is less
824 if other._sign < self._sign:
825 return -1
826 if self._sign < other._sign:
827 return 1
829 self_adjusted = self.adjusted()
830 other_adjusted = other.adjusted()
831 if self_adjusted == other_adjusted:
832 self_padded = self._int + '0'*(self._exp - other._exp)
833 other_padded = other._int + '0'*(other._exp - self._exp)
834 if self_padded == other_padded:
835 return 0
836 elif self_padded < other_padded:
837 return -(-1)**self._sign
838 else:
839 return (-1)**self._sign
840 elif self_adjusted > other_adjusted:
841 return (-1)**self._sign
842 else: # self_adjusted < other_adjusted
843 return -((-1)**self._sign)
845 # Note: The Decimal standard doesn't cover rich comparisons for
846 # Decimals. In particular, the specification is silent on the
847 # subject of what should happen for a comparison involving a NaN.
848 # We take the following approach:
850 # == comparisons involving a NaN always return False
851 # != comparisons involving a NaN always return True
852 # <, >, <= and >= comparisons involving a (quiet or signaling)
853 # NaN signal InvalidOperation, and return False if the
854 # InvalidOperation is not trapped.
856 # This behavior is designed to conform as closely as possible to
857 # that specified by IEEE 754.
859 def __eq__(self, other):
860 other = _convert_other(other)
861 if other is NotImplemented:
862 return other
863 if self.is_nan() or other.is_nan():
864 return False
865 return self._cmp(other) == 0
867 def __ne__(self, other):
868 other = _convert_other(other)
869 if other is NotImplemented:
870 return other
871 if self.is_nan() or other.is_nan():
872 return True
873 return self._cmp(other) != 0
875 def __lt__(self, other, context=None):
876 other = _convert_other(other)
877 if other is NotImplemented:
878 return other
879 ans = self._compare_check_nans(other, context)
880 if ans:
881 return False
882 return self._cmp(other) < 0
884 def __le__(self, other, context=None):
885 other = _convert_other(other)
886 if other is NotImplemented:
887 return other
888 ans = self._compare_check_nans(other, context)
889 if ans:
890 return False
891 return self._cmp(other) <= 0
893 def __gt__(self, other, context=None):
894 other = _convert_other(other)
895 if other is NotImplemented:
896 return other
897 ans = self._compare_check_nans(other, context)
898 if ans:
899 return False
900 return self._cmp(other) > 0
902 def __ge__(self, other, context=None):
903 other = _convert_other(other)
904 if other is NotImplemented:
905 return other
906 ans = self._compare_check_nans(other, context)
907 if ans:
908 return False
909 return self._cmp(other) >= 0
911 def compare(self, other, context=None):
912 """Compares one to another.
914 -1 => a < b
915 0 => a = b
916 1 => a > b
917 NaN => one is NaN
918 Like __cmp__, but returns Decimal instances.
920 other = _convert_other(other, raiseit=True)
922 # Compare(NaN, NaN) = NaN
923 if (self._is_special or other and other._is_special):
924 ans = self._check_nans(other, context)
925 if ans:
926 return ans
928 return Decimal(self._cmp(other))
930 def __hash__(self):
931 """x.__hash__() <==> hash(x)"""
932 # Decimal integers must hash the same as the ints
934 # The hash of a nonspecial noninteger Decimal must depend only
935 # on the value of that Decimal, and not on its representation.
936 # For example: hash(Decimal('100E-1')) == hash(Decimal('10')).
937 if self._is_special:
938 if self._isnan():
939 raise TypeError('Cannot hash a NaN value.')
940 return hash(str(self))
941 if not self:
942 return 0
943 if self._isinteger():
944 op = _WorkRep(self.to_integral_value())
945 # to make computation feasible for Decimals with large
946 # exponent, we use the fact that hash(n) == hash(m) for
947 # any two nonzero integers n and m such that (i) n and m
948 # have the same sign, and (ii) n is congruent to m modulo
949 # 2**64-1. So we can replace hash((-1)**s*c*10**e) with
950 # hash((-1)**s*c*pow(10, e, 2**64-1).
951 return hash((-1)**op.sign*op.int*pow(10, op.exp, 2**64-1))
952 # The value of a nonzero nonspecial Decimal instance is
953 # faithfully represented by the triple consisting of its sign,
954 # its adjusted exponent, and its coefficient with trailing
955 # zeros removed.
956 return hash((self._sign,
957 self._exp+len(self._int),
958 self._int.rstrip('0')))
960 def as_tuple(self):
961 """Represents the number as a triple tuple.
963 To show the internals exactly as they are.
965 return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)
967 def __repr__(self):
968 """Represents the number as an instance of Decimal."""
969 # Invariant: eval(repr(d)) == d
970 return "Decimal('%s')" % str(self)
972 def __str__(self, eng=False, context=None):
973 """Return string representation of the number in scientific notation.
975 Captures all of the information in the underlying representation.
978 sign = ['', '-'][self._sign]
979 if self._is_special:
980 if self._exp == 'F':
981 return sign + 'Infinity'
982 elif self._exp == 'n':
983 return sign + 'NaN' + self._int
984 else: # self._exp == 'N'
985 return sign + 'sNaN' + self._int
987 # number of digits of self._int to left of decimal point
988 leftdigits = self._exp + len(self._int)
990 # dotplace is number of digits of self._int to the left of the
991 # decimal point in the mantissa of the output string (that is,
992 # after adjusting the exponent)
993 if self._exp <= 0 and leftdigits > -6:
994 # no exponent required
995 dotplace = leftdigits
996 elif not eng:
997 # usual scientific notation: 1 digit on left of the point
998 dotplace = 1
999 elif self._int == '0':
1000 # engineering notation, zero
1001 dotplace = (leftdigits + 1) % 3 - 1
1002 else:
1003 # engineering notation, nonzero
1004 dotplace = (leftdigits - 1) % 3 + 1
1006 if dotplace <= 0:
1007 intpart = '0'
1008 fracpart = '.' + '0'*(-dotplace) + self._int
1009 elif dotplace >= len(self._int):
1010 intpart = self._int+'0'*(dotplace-len(self._int))
1011 fracpart = ''
1012 else:
1013 intpart = self._int[:dotplace]
1014 fracpart = '.' + self._int[dotplace:]
1015 if leftdigits == dotplace:
1016 exp = ''
1017 else:
1018 if context is None:
1019 context = getcontext()
1020 exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
1022 return sign + intpart + fracpart + exp
1024 def to_eng_string(self, context=None):
1025 """Convert to engineering-type string.
1027 Engineering notation has an exponent which is a multiple of 3, so there
1028 are up to 3 digits left of the decimal place.
1030 Same rules for when in exponential and when as a value as in __str__.
1032 return self.__str__(eng=True, context=context)
1034 def __neg__(self, context=None):
1035 """Returns a copy with the sign switched.
1037 Rounds, if it has reason.
1039 if self._is_special:
1040 ans = self._check_nans(context=context)
1041 if ans:
1042 return ans
1044 if not self:
1045 # -Decimal('0') is Decimal('0'), not Decimal('-0')
1046 ans = self.copy_abs()
1047 else:
1048 ans = self.copy_negate()
1050 if context is None:
1051 context = getcontext()
1052 return ans._fix(context)
1054 def __pos__(self, context=None):
1055 """Returns a copy, unless it is a sNaN.
1057 Rounds the number (if more then precision digits)
1059 if self._is_special:
1060 ans = self._check_nans(context=context)
1061 if ans:
1062 return ans
1064 if not self:
1065 # + (-0) = 0
1066 ans = self.copy_abs()
1067 else:
1068 ans = Decimal(self)
1070 if context is None:
1071 context = getcontext()
1072 return ans._fix(context)
1074 def __abs__(self, round=True, context=None):
1075 """Returns the absolute value of self.
1077 If the keyword argument 'round' is false, do not round. The
1078 expression self.__abs__(round=False) is equivalent to
1079 self.copy_abs().
1081 if not round:
1082 return self.copy_abs()
1084 if self._is_special:
1085 ans = self._check_nans(context=context)
1086 if ans:
1087 return ans
1089 if self._sign:
1090 ans = self.__neg__(context=context)
1091 else:
1092 ans = self.__pos__(context=context)
1094 return ans
1096 def __add__(self, other, context=None):
1097 """Returns self + other.
1099 -INF + INF (or the reverse) cause InvalidOperation errors.
1101 other = _convert_other(other)
1102 if other is NotImplemented:
1103 return other
1105 if context is None:
1106 context = getcontext()
1108 if self._is_special or other._is_special:
1109 ans = self._check_nans(other, context)
1110 if ans:
1111 return ans
1113 if self._isinfinity():
1114 # If both INF, same sign => same as both, opposite => error.
1115 if self._sign != other._sign and other._isinfinity():
1116 return context._raise_error(InvalidOperation, '-INF + INF')
1117 return Decimal(self)
1118 if other._isinfinity():
1119 return Decimal(other) # Can't both be infinity here
1121 exp = min(self._exp, other._exp)
1122 negativezero = 0
1123 if context.rounding == ROUND_FLOOR and self._sign != other._sign:
1124 # If the answer is 0, the sign should be negative, in this case.
1125 negativezero = 1
1127 if not self and not other:
1128 sign = min(self._sign, other._sign)
1129 if negativezero:
1130 sign = 1
1131 ans = _dec_from_triple(sign, '0', exp)
1132 ans = ans._fix(context)
1133 return ans
1134 if not self:
1135 exp = max(exp, other._exp - context.prec-1)
1136 ans = other._rescale(exp, context.rounding)
1137 ans = ans._fix(context)
1138 return ans
1139 if not other:
1140 exp = max(exp, self._exp - context.prec-1)
1141 ans = self._rescale(exp, context.rounding)
1142 ans = ans._fix(context)
1143 return ans
1145 op1 = _WorkRep(self)
1146 op2 = _WorkRep(other)
1147 op1, op2 = _normalize(op1, op2, context.prec)
1149 result = _WorkRep()
1150 if op1.sign != op2.sign:
1151 # Equal and opposite
1152 if op1.int == op2.int:
1153 ans = _dec_from_triple(negativezero, '0', exp)
1154 ans = ans._fix(context)
1155 return ans
1156 if op1.int < op2.int:
1157 op1, op2 = op2, op1
1158 # OK, now abs(op1) > abs(op2)
1159 if op1.sign == 1:
1160 result.sign = 1
1161 op1.sign, op2.sign = op2.sign, op1.sign
1162 else:
1163 result.sign = 0
1164 # So we know the sign, and op1 > 0.
1165 elif op1.sign == 1:
1166 result.sign = 1
1167 op1.sign, op2.sign = (0, 0)
1168 else:
1169 result.sign = 0
1170 # Now, op1 > abs(op2) > 0
1172 if op2.sign == 0:
1173 result.int = op1.int + op2.int
1174 else:
1175 result.int = op1.int - op2.int
1177 result.exp = op1.exp
1178 ans = Decimal(result)
1179 ans = ans._fix(context)
1180 return ans
1182 __radd__ = __add__
1184 def __sub__(self, other, context=None):
1185 """Return self - other"""
1186 other = _convert_other(other)
1187 if other is NotImplemented:
1188 return other
1190 if self._is_special or other._is_special:
1191 ans = self._check_nans(other, context=context)
1192 if ans:
1193 return ans
1195 # self - other is computed as self + other.copy_negate()
1196 return self.__add__(other.copy_negate(), context=context)
1198 def __rsub__(self, other, context=None):
1199 """Return other - self"""
1200 other = _convert_other(other)
1201 if other is NotImplemented:
1202 return other
1204 return other.__sub__(self, context=context)
1206 def __mul__(self, other, context=None):
1207 """Return self * other.
1209 (+-) INF * 0 (or its reverse) raise InvalidOperation.
1211 other = _convert_other(other)
1212 if other is NotImplemented:
1213 return other
1215 if context is None:
1216 context = getcontext()
1218 resultsign = 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():
1226 if not other:
1227 return context._raise_error(InvalidOperation, '(+-)INF * 0')
1228 return _SignedInfinity[resultsign]
1230 if other._isinfinity():
1231 if not self:
1232 return context._raise_error(InvalidOperation, '0 * (+-)INF')
1233 return _SignedInfinity[resultsign]
1235 resultexp = self._exp + other._exp
1237 # Special case for multiplying by zero
1238 if not self or not other:
1239 ans = _dec_from_triple(resultsign, '0', resultexp)
1240 # Fixing in case the exponent is out of bounds
1241 ans = ans._fix(context)
1242 return ans
1244 # Special case for multiplying by power of 10
1245 if self._int == '1':
1246 ans = _dec_from_triple(resultsign, other._int, resultexp)
1247 ans = ans._fix(context)
1248 return ans
1249 if other._int == '1':
1250 ans = _dec_from_triple(resultsign, self._int, resultexp)
1251 ans = ans._fix(context)
1252 return ans
1254 op1 = _WorkRep(self)
1255 op2 = _WorkRep(other)
1257 ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
1258 ans = ans._fix(context)
1260 return ans
1261 __rmul__ = __mul__
1263 def __truediv__(self, other, context=None):
1264 """Return self / other."""
1265 other = _convert_other(other)
1266 if other is NotImplemented:
1267 return NotImplemented
1269 if context is None:
1270 context = getcontext()
1272 sign = self._sign ^ other._sign
1274 if self._is_special or other._is_special:
1275 ans = self._check_nans(other, context)
1276 if ans:
1277 return ans
1279 if self._isinfinity() and other._isinfinity():
1280 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
1282 if self._isinfinity():
1283 return _SignedInfinity[sign]
1285 if other._isinfinity():
1286 context._raise_error(Clamped, 'Division by infinity')
1287 return _dec_from_triple(sign, '0', context.Etiny())
1289 # Special cases for zeroes
1290 if not other:
1291 if not self:
1292 return context._raise_error(DivisionUndefined, '0 / 0')
1293 return context._raise_error(DivisionByZero, 'x / 0', sign)
1295 if not self:
1296 exp = self._exp - other._exp
1297 coeff = 0
1298 else:
1299 # OK, so neither = 0, INF or NaN
1300 shift = len(other._int) - len(self._int) + context.prec + 1
1301 exp = self._exp - other._exp - shift
1302 op1 = _WorkRep(self)
1303 op2 = _WorkRep(other)
1304 if shift >= 0:
1305 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
1306 else:
1307 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
1308 if remainder:
1309 # result is not exact; adjust to ensure correct rounding
1310 if coeff % 5 == 0:
1311 coeff += 1
1312 else:
1313 # result is exact; get as close to ideal exponent as possible
1314 ideal_exp = self._exp - other._exp
1315 while exp < ideal_exp and coeff % 10 == 0:
1316 coeff //= 10
1317 exp += 1
1319 ans = _dec_from_triple(sign, str(coeff), exp)
1320 return ans._fix(context)
1322 def _divide(self, other, context):
1323 """Return (self // other, self % other), to context.prec precision.
1325 Assumes that neither self nor other is a NaN, that self is not
1326 infinite and that other is nonzero.
1328 sign = self._sign ^ other._sign
1329 if other._isinfinity():
1330 ideal_exp = self._exp
1331 else:
1332 ideal_exp = min(self._exp, other._exp)
1334 expdiff = self.adjusted() - other.adjusted()
1335 if not self or other._isinfinity() or expdiff <= -2:
1336 return (_dec_from_triple(sign, '0', 0),
1337 self._rescale(ideal_exp, context.rounding))
1338 if expdiff <= context.prec:
1339 op1 = _WorkRep(self)
1340 op2 = _WorkRep(other)
1341 if op1.exp >= op2.exp:
1342 op1.int *= 10**(op1.exp - op2.exp)
1343 else:
1344 op2.int *= 10**(op2.exp - op1.exp)
1345 q, r = divmod(op1.int, op2.int)
1346 if q < 10**context.prec:
1347 return (_dec_from_triple(sign, str(q), 0),
1348 _dec_from_triple(self._sign, str(r), ideal_exp))
1350 # Here the quotient is too large to be representable
1351 ans = context._raise_error(DivisionImpossible,
1352 'quotient too large in //, % or divmod')
1353 return ans, ans
1355 def __rtruediv__(self, other, context=None):
1356 """Swaps self/other and returns __truediv__."""
1357 other = _convert_other(other)
1358 if other is NotImplemented:
1359 return other
1360 return other.__truediv__(self, context=context)
1362 __div__ = __truediv__
1363 __rdiv__ = __rtruediv__
1365 def __divmod__(self, other, context=None):
1367 Return (self // other, self % other)
1369 other = _convert_other(other)
1370 if other is NotImplemented:
1371 return other
1373 if context is None:
1374 context = getcontext()
1376 ans = self._check_nans(other, context)
1377 if ans:
1378 return (ans, ans)
1380 sign = self._sign ^ other._sign
1381 if self._isinfinity():
1382 if other._isinfinity():
1383 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
1384 return ans, ans
1385 else:
1386 return (_SignedInfinity[sign],
1387 context._raise_error(InvalidOperation, 'INF % x'))
1389 if not other:
1390 if not self:
1391 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
1392 return ans, ans
1393 else:
1394 return (context._raise_error(DivisionByZero, 'x // 0', sign),
1395 context._raise_error(InvalidOperation, 'x % 0'))
1397 quotient, remainder = self._divide(other, context)
1398 remainder = remainder._fix(context)
1399 return quotient, remainder
1401 def __rdivmod__(self, other, context=None):
1402 """Swaps self/other and returns __divmod__."""
1403 other = _convert_other(other)
1404 if other is NotImplemented:
1405 return other
1406 return other.__divmod__(self, context=context)
1408 def __mod__(self, other, context=None):
1410 self % other
1412 other = _convert_other(other)
1413 if other is NotImplemented:
1414 return other
1416 if context is None:
1417 context = getcontext()
1419 ans = self._check_nans(other, context)
1420 if ans:
1421 return ans
1423 if self._isinfinity():
1424 return context._raise_error(InvalidOperation, 'INF % x')
1425 elif not other:
1426 if self:
1427 return context._raise_error(InvalidOperation, 'x % 0')
1428 else:
1429 return context._raise_error(DivisionUndefined, '0 % 0')
1431 remainder = self._divide(other, context)[1]
1432 remainder = remainder._fix(context)
1433 return remainder
1435 def __rmod__(self, other, context=None):
1436 """Swaps self/other and returns __mod__."""
1437 other = _convert_other(other)
1438 if other is NotImplemented:
1439 return other
1440 return other.__mod__(self, context=context)
1442 def remainder_near(self, other, context=None):
1444 Remainder nearest to 0- abs(remainder-near) <= other/2
1446 if context is None:
1447 context = getcontext()
1449 other = _convert_other(other, raiseit=True)
1451 ans = self._check_nans(other, context)
1452 if ans:
1453 return ans
1455 # self == +/-infinity -> InvalidOperation
1456 if self._isinfinity():
1457 return context._raise_error(InvalidOperation,
1458 'remainder_near(infinity, x)')
1460 # other == 0 -> either InvalidOperation or DivisionUndefined
1461 if not other:
1462 if self:
1463 return context._raise_error(InvalidOperation,
1464 'remainder_near(x, 0)')
1465 else:
1466 return context._raise_error(DivisionUndefined,
1467 'remainder_near(0, 0)')
1469 # other = +/-infinity -> remainder = self
1470 if other._isinfinity():
1471 ans = Decimal(self)
1472 return ans._fix(context)
1474 # self = 0 -> remainder = self, with ideal exponent
1475 ideal_exponent = min(self._exp, other._exp)
1476 if not self:
1477 ans = _dec_from_triple(self._sign, '0', ideal_exponent)
1478 return ans._fix(context)
1480 # catch most cases of large or small quotient
1481 expdiff = self.adjusted() - other.adjusted()
1482 if expdiff >= context.prec + 1:
1483 # expdiff >= prec+1 => abs(self/other) > 10**prec
1484 return context._raise_error(DivisionImpossible)
1485 if expdiff <= -2:
1486 # expdiff <= -2 => abs(self/other) < 0.1
1487 ans = self._rescale(ideal_exponent, context.rounding)
1488 return ans._fix(context)
1490 # adjust both arguments to have the same exponent, then divide
1491 op1 = _WorkRep(self)
1492 op2 = _WorkRep(other)
1493 if op1.exp >= op2.exp:
1494 op1.int *= 10**(op1.exp - op2.exp)
1495 else:
1496 op2.int *= 10**(op2.exp - op1.exp)
1497 q, r = divmod(op1.int, op2.int)
1498 # remainder is r*10**ideal_exponent; other is +/-op2.int *
1499 # 10**ideal_exponent. Apply correction to ensure that
1500 # abs(remainder) <= abs(other)/2
1501 if 2*r + (q&1) > op2.int:
1502 r -= op2.int
1503 q += 1
1505 if q >= 10**context.prec:
1506 return context._raise_error(DivisionImpossible)
1508 # result has same sign as self unless r is negative
1509 sign = self._sign
1510 if r < 0:
1511 sign = 1-sign
1512 r = -r
1514 ans = _dec_from_triple(sign, str(r), ideal_exponent)
1515 return ans._fix(context)
1517 def __floordiv__(self, other, context=None):
1518 """self // other"""
1519 other = _convert_other(other)
1520 if other is NotImplemented:
1521 return other
1523 if context is None:
1524 context = getcontext()
1526 ans = self._check_nans(other, context)
1527 if ans:
1528 return ans
1530 if self._isinfinity():
1531 if other._isinfinity():
1532 return context._raise_error(InvalidOperation, 'INF // INF')
1533 else:
1534 return _SignedInfinity[self._sign ^ other._sign]
1536 if not other:
1537 if self:
1538 return context._raise_error(DivisionByZero, 'x // 0',
1539 self._sign ^ other._sign)
1540 else:
1541 return context._raise_error(DivisionUndefined, '0 // 0')
1543 return self._divide(other, context)[0]
1545 def __rfloordiv__(self, other, context=None):
1546 """Swaps self/other and returns __floordiv__."""
1547 other = _convert_other(other)
1548 if other is NotImplemented:
1549 return other
1550 return other.__floordiv__(self, context=context)
1552 def __float__(self):
1553 """Float representation."""
1554 return float(str(self))
1556 def __int__(self):
1557 """Converts self to an int, truncating if necessary."""
1558 if self._is_special:
1559 if self._isnan():
1560 context = getcontext()
1561 return context._raise_error(InvalidContext)
1562 elif self._isinfinity():
1563 raise OverflowError("Cannot convert infinity to int")
1564 s = (-1)**self._sign
1565 if self._exp >= 0:
1566 return s*int(self._int)*10**self._exp
1567 else:
1568 return s*int(self._int[:self._exp] or '0')
1570 __trunc__ = __int__
1572 def real(self):
1573 return self
1574 real = property(real)
1576 def imag(self):
1577 return Decimal(0)
1578 imag = property(imag)
1580 def conjugate(self):
1581 return self
1583 def __complex__(self):
1584 return complex(float(self))
1586 def __long__(self):
1587 """Converts to a long.
1589 Equivalent to long(int(self))
1591 return long(self.__int__())
1593 def _fix_nan(self, context):
1594 """Decapitate the payload of a NaN to fit the context"""
1595 payload = self._int
1597 # maximum length of payload is precision if _clamp=0,
1598 # precision-1 if _clamp=1.
1599 max_payload_len = context.prec - context._clamp
1600 if len(payload) > max_payload_len:
1601 payload = payload[len(payload)-max_payload_len:].lstrip('0')
1602 return _dec_from_triple(self._sign, payload, self._exp, True)
1603 return Decimal(self)
1605 def _fix(self, context):
1606 """Round if it is necessary to keep self within prec precision.
1608 Rounds and fixes the exponent. Does not raise on a sNaN.
1610 Arguments:
1611 self - Decimal instance
1612 context - context used.
1615 if self._is_special:
1616 if self._isnan():
1617 # decapitate payload if necessary
1618 return self._fix_nan(context)
1619 else:
1620 # self is +/-Infinity; return unaltered
1621 return Decimal(self)
1623 # if self is zero then exponent should be between Etiny and
1624 # Emax if _clamp==0, and between Etiny and Etop if _clamp==1.
1625 Etiny = context.Etiny()
1626 Etop = context.Etop()
1627 if not self:
1628 exp_max = [context.Emax, Etop][context._clamp]
1629 new_exp = min(max(self._exp, Etiny), exp_max)
1630 if new_exp != self._exp:
1631 context._raise_error(Clamped)
1632 return _dec_from_triple(self._sign, '0', new_exp)
1633 else:
1634 return Decimal(self)
1636 # exp_min is the smallest allowable exponent of the result,
1637 # equal to max(self.adjusted()-context.prec+1, Etiny)
1638 exp_min = len(self._int) + self._exp - context.prec
1639 if exp_min > Etop:
1640 # overflow: exp_min > Etop iff self.adjusted() > Emax
1641 context._raise_error(Inexact)
1642 context._raise_error(Rounded)
1643 return context._raise_error(Overflow, 'above Emax', self._sign)
1644 self_is_subnormal = exp_min < Etiny
1645 if self_is_subnormal:
1646 context._raise_error(Subnormal)
1647 exp_min = Etiny
1649 # round if self has too many digits
1650 if self._exp < exp_min:
1651 context._raise_error(Rounded)
1652 digits = len(self._int) + self._exp - exp_min
1653 if digits < 0:
1654 self = _dec_from_triple(self._sign, '1', exp_min-1)
1655 digits = 0
1656 this_function = getattr(self, self._pick_rounding_function[context.rounding])
1657 changed = this_function(digits)
1658 coeff = self._int[:digits] or '0'
1659 if changed == 1:
1660 coeff = str(int(coeff)+1)
1661 ans = _dec_from_triple(self._sign, coeff, exp_min)
1663 if changed:
1664 context._raise_error(Inexact)
1665 if self_is_subnormal:
1666 context._raise_error(Underflow)
1667 if not ans:
1668 # raise Clamped on underflow to 0
1669 context._raise_error(Clamped)
1670 elif len(ans._int) == context.prec+1:
1671 # we get here only if rescaling rounds the
1672 # cofficient up to exactly 10**context.prec
1673 if ans._exp < Etop:
1674 ans = _dec_from_triple(ans._sign,
1675 ans._int[:-1], ans._exp+1)
1676 else:
1677 # Inexact and Rounded have already been raised
1678 ans = context._raise_error(Overflow, 'above Emax',
1679 self._sign)
1680 return ans
1682 # fold down if _clamp == 1 and self has too few digits
1683 if context._clamp == 1 and self._exp > Etop:
1684 context._raise_error(Clamped)
1685 self_padded = self._int + '0'*(self._exp - Etop)
1686 return _dec_from_triple(self._sign, self_padded, Etop)
1688 # here self was representable to begin with; return unchanged
1689 return Decimal(self)
1691 _pick_rounding_function = {}
1693 # for each of the rounding functions below:
1694 # self is a finite, nonzero Decimal
1695 # prec is an integer satisfying 0 <= prec < len(self._int)
1697 # each function returns either -1, 0, or 1, as follows:
1698 # 1 indicates that self should be rounded up (away from zero)
1699 # 0 indicates that self should be truncated, and that all the
1700 # digits to be truncated are zeros (so the value is unchanged)
1701 # -1 indicates that there are nonzero digits to be truncated
1703 def _round_down(self, prec):
1704 """Also known as round-towards-0, truncate."""
1705 if _all_zeros(self._int, prec):
1706 return 0
1707 else:
1708 return -1
1710 def _round_up(self, prec):
1711 """Rounds away from 0."""
1712 return -self._round_down(prec)
1714 def _round_half_up(self, prec):
1715 """Rounds 5 up (away from 0)"""
1716 if self._int[prec] in '56789':
1717 return 1
1718 elif _all_zeros(self._int, prec):
1719 return 0
1720 else:
1721 return -1
1723 def _round_half_down(self, prec):
1724 """Round 5 down"""
1725 if _exact_half(self._int, prec):
1726 return -1
1727 else:
1728 return self._round_half_up(prec)
1730 def _round_half_even(self, prec):
1731 """Round 5 to even, rest to nearest."""
1732 if _exact_half(self._int, prec) and \
1733 (prec == 0 or self._int[prec-1] in '02468'):
1734 return -1
1735 else:
1736 return self._round_half_up(prec)
1738 def _round_ceiling(self, prec):
1739 """Rounds up (not away from 0 if negative.)"""
1740 if self._sign:
1741 return self._round_down(prec)
1742 else:
1743 return -self._round_down(prec)
1745 def _round_floor(self, prec):
1746 """Rounds down (not towards 0 if negative)"""
1747 if not self._sign:
1748 return self._round_down(prec)
1749 else:
1750 return -self._round_down(prec)
1752 def _round_05up(self, prec):
1753 """Round down unless digit prec-1 is 0 or 5."""
1754 if prec and self._int[prec-1] not in '05':
1755 return self._round_down(prec)
1756 else:
1757 return -self._round_down(prec)
1759 def fma(self, other, third, context=None):
1760 """Fused multiply-add.
1762 Returns self*other+third with no rounding of the intermediate
1763 product self*other.
1765 self and other are multiplied together, with no rounding of
1766 the result. The third operand is then added to the result,
1767 and a single final rounding is performed.
1770 other = _convert_other(other, raiseit=True)
1772 # compute product; raise InvalidOperation if either operand is
1773 # a signaling NaN or if the product is zero times infinity.
1774 if self._is_special or other._is_special:
1775 if context is None:
1776 context = getcontext()
1777 if self._exp == 'N':
1778 return context._raise_error(InvalidOperation, 'sNaN', self)
1779 if other._exp == 'N':
1780 return context._raise_error(InvalidOperation, 'sNaN', other)
1781 if self._exp == 'n':
1782 product = self
1783 elif other._exp == 'n':
1784 product = other
1785 elif self._exp == 'F':
1786 if not other:
1787 return context._raise_error(InvalidOperation,
1788 'INF * 0 in fma')
1789 product = _SignedInfinity[self._sign ^ other._sign]
1790 elif other._exp == 'F':
1791 if not self:
1792 return context._raise_error(InvalidOperation,
1793 '0 * INF in fma')
1794 product = _SignedInfinity[self._sign ^ other._sign]
1795 else:
1796 product = _dec_from_triple(self._sign ^ other._sign,
1797 str(int(self._int) * int(other._int)),
1798 self._exp + other._exp)
1800 third = _convert_other(third, raiseit=True)
1801 return product.__add__(third, context)
1803 def _power_modulo(self, other, modulo, context=None):
1804 """Three argument version of __pow__"""
1806 # if can't convert other and modulo to Decimal, raise
1807 # TypeError; there's no point returning NotImplemented (no
1808 # equivalent of __rpow__ for three argument pow)
1809 other = _convert_other(other, raiseit=True)
1810 modulo = _convert_other(modulo, raiseit=True)
1812 if context is None:
1813 context = getcontext()
1815 # deal with NaNs: if there are any sNaNs then first one wins,
1816 # (i.e. behaviour for NaNs is identical to that of fma)
1817 self_is_nan = self._isnan()
1818 other_is_nan = other._isnan()
1819 modulo_is_nan = modulo._isnan()
1820 if self_is_nan or other_is_nan or modulo_is_nan:
1821 if self_is_nan == 2:
1822 return context._raise_error(InvalidOperation, 'sNaN',
1823 self)
1824 if other_is_nan == 2:
1825 return context._raise_error(InvalidOperation, 'sNaN',
1826 other)
1827 if modulo_is_nan == 2:
1828 return context._raise_error(InvalidOperation, 'sNaN',
1829 modulo)
1830 if self_is_nan:
1831 return self._fix_nan(context)
1832 if other_is_nan:
1833 return other._fix_nan(context)
1834 return modulo._fix_nan(context)
1836 # check inputs: we apply same restrictions as Python's pow()
1837 if not (self._isinteger() and
1838 other._isinteger() and
1839 modulo._isinteger()):
1840 return context._raise_error(InvalidOperation,
1841 'pow() 3rd argument not allowed '
1842 'unless all arguments are integers')
1843 if other < 0:
1844 return context._raise_error(InvalidOperation,
1845 'pow() 2nd argument cannot be '
1846 'negative when 3rd argument specified')
1847 if not modulo:
1848 return context._raise_error(InvalidOperation,
1849 'pow() 3rd argument cannot be 0')
1851 # additional restriction for decimal: the modulus must be less
1852 # than 10**prec in absolute value
1853 if modulo.adjusted() >= context.prec:
1854 return context._raise_error(InvalidOperation,
1855 'insufficient precision: pow() 3rd '
1856 'argument must not have more than '
1857 'precision digits')
1859 # define 0**0 == NaN, for consistency with two-argument pow
1860 # (even though it hurts!)
1861 if not other and not self:
1862 return context._raise_error(InvalidOperation,
1863 'at least one of pow() 1st argument '
1864 'and 2nd argument must be nonzero ;'
1865 '0**0 is not defined')
1867 # compute sign of result
1868 if other._iseven():
1869 sign = 0
1870 else:
1871 sign = self._sign
1873 # convert modulo to a Python integer, and self and other to
1874 # Decimal integers (i.e. force their exponents to be >= 0)
1875 modulo = abs(int(modulo))
1876 base = _WorkRep(self.to_integral_value())
1877 exponent = _WorkRep(other.to_integral_value())
1879 # compute result using integer pow()
1880 base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
1881 for i in xrange(exponent.exp):
1882 base = pow(base, 10, modulo)
1883 base = pow(base, exponent.int, modulo)
1885 return _dec_from_triple(sign, str(base), 0)
1887 def _power_exact(self, other, p):
1888 """Attempt to compute self**other exactly.
1890 Given Decimals self and other and an integer p, attempt to
1891 compute an exact result for the power self**other, with p
1892 digits of precision. Return None if self**other is not
1893 exactly representable in p digits.
1895 Assumes that elimination of special cases has already been
1896 performed: self and other must both be nonspecial; self must
1897 be positive and not numerically equal to 1; other must be
1898 nonzero. For efficiency, other._exp should not be too large,
1899 so that 10**abs(other._exp) is a feasible calculation."""
1901 # In the comments below, we write x for the value of self and
1902 # y for the value of other. Write x = xc*10**xe and y =
1903 # yc*10**ye.
1905 # The main purpose of this method is to identify the *failure*
1906 # of x**y to be exactly representable with as little effort as
1907 # possible. So we look for cheap and easy tests that
1908 # eliminate the possibility of x**y being exact. Only if all
1909 # these tests are passed do we go on to actually compute x**y.
1911 # Here's the main idea. First normalize both x and y. We
1912 # express y as a rational m/n, with m and n relatively prime
1913 # and n>0. Then for x**y to be exactly representable (at
1914 # *any* precision), xc must be the nth power of a positive
1915 # integer and xe must be divisible by n. If m is negative
1916 # then additionally xc must be a power of either 2 or 5, hence
1917 # a power of 2**n or 5**n.
1919 # There's a limit to how small |y| can be: if y=m/n as above
1920 # then:
1922 # (1) if xc != 1 then for the result to be representable we
1923 # need xc**(1/n) >= 2, and hence also xc**|y| >= 2. So
1924 # if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
1925 # 2**(1/|y|), hence xc**|y| < 2 and the result is not
1926 # representable.
1928 # (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1. Hence if
1929 # |y| < 1/|xe| then the result is not representable.
1931 # Note that since x is not equal to 1, at least one of (1) and
1932 # (2) must apply. Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
1933 # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
1935 # There's also a limit to how large y can be, at least if it's
1936 # positive: the normalized result will have coefficient xc**y,
1937 # so if it's representable then xc**y < 10**p, and y <
1938 # p/log10(xc). Hence if y*log10(xc) >= p then the result is
1939 # not exactly representable.
1941 # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
1942 # so |y| < 1/xe and the result is not representable.
1943 # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
1944 # < 1/nbits(xc).
1946 x = _WorkRep(self)
1947 xc, xe = x.int, x.exp
1948 while xc % 10 == 0:
1949 xc //= 10
1950 xe += 1
1952 y = _WorkRep(other)
1953 yc, ye = y.int, y.exp
1954 while yc % 10 == 0:
1955 yc //= 10
1956 ye += 1
1958 # case where xc == 1: result is 10**(xe*y), with xe*y
1959 # required to be an integer
1960 if xc == 1:
1961 if ye >= 0:
1962 exponent = xe*yc*10**ye
1963 else:
1964 exponent, remainder = divmod(xe*yc, 10**-ye)
1965 if remainder:
1966 return None
1967 if y.sign == 1:
1968 exponent = -exponent
1969 # if other is a nonnegative integer, use ideal exponent
1970 if other._isinteger() and other._sign == 0:
1971 ideal_exponent = self._exp*int(other)
1972 zeros = min(exponent-ideal_exponent, p-1)
1973 else:
1974 zeros = 0
1975 return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
1977 # case where y is negative: xc must be either a power
1978 # of 2 or a power of 5.
1979 if y.sign == 1:
1980 last_digit = xc % 10
1981 if last_digit in (2,4,6,8):
1982 # quick test for power of 2
1983 if xc & -xc != xc:
1984 return None
1985 # now xc is a power of 2; e is its exponent
1986 e = _nbits(xc)-1
1987 # find e*y and xe*y; both must be integers
1988 if ye >= 0:
1989 y_as_int = yc*10**ye
1990 e = e*y_as_int
1991 xe = xe*y_as_int
1992 else:
1993 ten_pow = 10**-ye
1994 e, remainder = divmod(e*yc, ten_pow)
1995 if remainder:
1996 return None
1997 xe, remainder = divmod(xe*yc, ten_pow)
1998 if remainder:
1999 return None
2001 if e*65 >= p*93: # 93/65 > log(10)/log(5)
2002 return None
2003 xc = 5**e
2005 elif last_digit == 5:
2006 # e >= log_5(xc) if xc is a power of 5; we have
2007 # equality all the way up to xc=5**2658
2008 e = _nbits(xc)*28//65
2009 xc, remainder = divmod(5**e, xc)
2010 if remainder:
2011 return None
2012 while xc % 5 == 0:
2013 xc //= 5
2014 e -= 1
2015 if ye >= 0:
2016 y_as_integer = yc*10**ye
2017 e = e*y_as_integer
2018 xe = xe*y_as_integer
2019 else:
2020 ten_pow = 10**-ye
2021 e, remainder = divmod(e*yc, ten_pow)
2022 if remainder:
2023 return None
2024 xe, remainder = divmod(xe*yc, ten_pow)
2025 if remainder:
2026 return None
2027 if e*3 >= p*10: # 10/3 > log(10)/log(2)
2028 return None
2029 xc = 2**e
2030 else:
2031 return None
2033 if xc >= 10**p:
2034 return None
2035 xe = -e-xe
2036 return _dec_from_triple(0, str(xc), xe)
2038 # now y is positive; find m and n such that y = m/n
2039 if ye >= 0:
2040 m, n = yc*10**ye, 1
2041 else:
2042 if xe != 0 and len(str(abs(yc*xe))) <= -ye:
2043 return None
2044 xc_bits = _nbits(xc)
2045 if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
2046 return None
2047 m, n = yc, 10**(-ye)
2048 while m % 2 == n % 2 == 0:
2049 m //= 2
2050 n //= 2
2051 while m % 5 == n % 5 == 0:
2052 m //= 5
2053 n //= 5
2055 # compute nth root of xc*10**xe
2056 if n > 1:
2057 # if 1 < xc < 2**n then xc isn't an nth power
2058 if xc != 1 and xc_bits <= n:
2059 return None
2061 xe, rem = divmod(xe, n)
2062 if rem != 0:
2063 return None
2065 # compute nth root of xc using Newton's method
2066 a = 1L << -(-_nbits(xc)//n) # initial estimate
2067 while True:
2068 q, r = divmod(xc, a**(n-1))
2069 if a <= q:
2070 break
2071 else:
2072 a = (a*(n-1) + q)//n
2073 if not (a == q and r == 0):
2074 return None
2075 xc = a
2077 # now xc*10**xe is the nth root of the original xc*10**xe
2078 # compute mth power of xc*10**xe
2080 # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
2081 # 10**p and the result is not representable.
2082 if xc > 1 and m > p*100//_log10_lb(xc):
2083 return None
2084 xc = xc**m
2085 xe *= m
2086 if xc > 10**p:
2087 return None
2089 # by this point the result *is* exactly representable
2090 # adjust the exponent to get as close as possible to the ideal
2091 # exponent, if necessary
2092 str_xc = str(xc)
2093 if other._isinteger() and other._sign == 0:
2094 ideal_exponent = self._exp*int(other)
2095 zeros = min(xe-ideal_exponent, p-len(str_xc))
2096 else:
2097 zeros = 0
2098 return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)
2100 def __pow__(self, other, modulo=None, context=None):
2101 """Return self ** other [ % modulo].
2103 With two arguments, compute self**other.
2105 With three arguments, compute (self**other) % modulo. For the
2106 three argument form, the following restrictions on the
2107 arguments hold:
2109 - all three arguments must be integral
2110 - other must be nonnegative
2111 - either self or other (or both) must be nonzero
2112 - modulo must be nonzero and must have at most p digits,
2113 where p is the context precision.
2115 If any of these restrictions is violated the InvalidOperation
2116 flag is raised.
2118 The result of pow(self, other, modulo) is identical to the
2119 result that would be obtained by computing (self**other) %
2120 modulo with unbounded precision, but is computed more
2121 efficiently. It is always exact.
2124 if modulo is not None:
2125 return self._power_modulo(other, modulo, context)
2127 other = _convert_other(other)
2128 if other is NotImplemented:
2129 return other
2131 if context is None:
2132 context = getcontext()
2134 # either argument is a NaN => result is NaN
2135 ans = self._check_nans(other, context)
2136 if ans:
2137 return ans
2139 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2140 if not other:
2141 if not self:
2142 return context._raise_error(InvalidOperation, '0 ** 0')
2143 else:
2144 return _One
2146 # result has sign 1 iff self._sign is 1 and other is an odd integer
2147 result_sign = 0
2148 if self._sign == 1:
2149 if other._isinteger():
2150 if not other._iseven():
2151 result_sign = 1
2152 else:
2153 # -ve**noninteger = NaN
2154 # (-0)**noninteger = 0**noninteger
2155 if self:
2156 return context._raise_error(InvalidOperation,
2157 'x ** y with x negative and y not an integer')
2158 # negate self, without doing any unwanted rounding
2159 self = self.copy_negate()
2161 # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
2162 if not self:
2163 if other._sign == 0:
2164 return _dec_from_triple(result_sign, '0', 0)
2165 else:
2166 return _SignedInfinity[result_sign]
2168 # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
2169 if self._isinfinity():
2170 if other._sign == 0:
2171 return _SignedInfinity[result_sign]
2172 else:
2173 return _dec_from_triple(result_sign, '0', 0)
2175 # 1**other = 1, but the choice of exponent and the flags
2176 # depend on the exponent of self, and on whether other is a
2177 # positive integer, a negative integer, or neither
2178 if self == _One:
2179 if other._isinteger():
2180 # exp = max(self._exp*max(int(other), 0),
2181 # 1-context.prec) but evaluating int(other) directly
2182 # is dangerous until we know other is small (other
2183 # could be 1e999999999)
2184 if other._sign == 1:
2185 multiplier = 0
2186 elif other > context.prec:
2187 multiplier = context.prec
2188 else:
2189 multiplier = int(other)
2191 exp = self._exp * multiplier
2192 if exp < 1-context.prec:
2193 exp = 1-context.prec
2194 context._raise_error(Rounded)
2195 else:
2196 context._raise_error(Inexact)
2197 context._raise_error(Rounded)
2198 exp = 1-context.prec
2200 return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
2202 # compute adjusted exponent of self
2203 self_adj = self.adjusted()
2205 # self ** infinity is infinity if self > 1, 0 if self < 1
2206 # self ** -infinity is infinity if self < 1, 0 if self > 1
2207 if other._isinfinity():
2208 if (other._sign == 0) == (self_adj < 0):
2209 return _dec_from_triple(result_sign, '0', 0)
2210 else:
2211 return _SignedInfinity[result_sign]
2213 # from here on, the result always goes through the call
2214 # to _fix at the end of this function.
2215 ans = None
2217 # crude test to catch cases of extreme overflow/underflow. If
2218 # log10(self)*other >= 10**bound and bound >= len(str(Emax))
2219 # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
2220 # self**other >= 10**(Emax+1), so overflow occurs. The test
2221 # for underflow is similar.
2222 bound = self._log10_exp_bound() + other.adjusted()
2223 if (self_adj >= 0) == (other._sign == 0):
2224 # self > 1 and other +ve, or self < 1 and other -ve
2225 # possibility of overflow
2226 if bound >= len(str(context.Emax)):
2227 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
2228 else:
2229 # self > 1 and other -ve, or self < 1 and other +ve
2230 # possibility of underflow to 0
2231 Etiny = context.Etiny()
2232 if bound >= len(str(-Etiny)):
2233 ans = _dec_from_triple(result_sign, '1', Etiny-1)
2235 # try for an exact result with precision +1
2236 if ans is None:
2237 ans = self._power_exact(other, context.prec + 1)
2238 if ans is not None and result_sign == 1:
2239 ans = _dec_from_triple(1, ans._int, ans._exp)
2241 # usual case: inexact result, x**y computed directly as exp(y*log(x))
2242 if ans is None:
2243 p = context.prec
2244 x = _WorkRep(self)
2245 xc, xe = x.int, x.exp
2246 y = _WorkRep(other)
2247 yc, ye = y.int, y.exp
2248 if y.sign == 1:
2249 yc = -yc
2251 # compute correctly rounded result: start with precision +3,
2252 # then increase precision until result is unambiguously roundable
2253 extra = 3
2254 while True:
2255 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
2256 if coeff % (5*10**(len(str(coeff))-p-1)):
2257 break
2258 extra += 3
2260 ans = _dec_from_triple(result_sign, str(coeff), exp)
2262 # the specification says that for non-integer other we need to
2263 # raise Inexact, even when the result is actually exact. In
2264 # the same way, we need to raise Underflow here if the result
2265 # is subnormal. (The call to _fix will take care of raising
2266 # Rounded and Subnormal, as usual.)
2267 if not other._isinteger():
2268 context._raise_error(Inexact)
2269 # pad with zeros up to length context.prec+1 if necessary
2270 if len(ans._int) <= context.prec:
2271 expdiff = context.prec+1 - len(ans._int)
2272 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
2273 ans._exp-expdiff)
2274 if ans.adjusted() < context.Emin:
2275 context._raise_error(Underflow)
2277 # unlike exp, ln and log10, the power function respects the
2278 # rounding mode; no need to use ROUND_HALF_EVEN here
2279 ans = ans._fix(context)
2280 return ans
2282 def __rpow__(self, other, context=None):
2283 """Swaps self/other and returns __pow__."""
2284 other = _convert_other(other)
2285 if other is NotImplemented:
2286 return other
2287 return other.__pow__(self, context=context)
2289 def normalize(self, context=None):
2290 """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
2292 if context is None:
2293 context = getcontext()
2295 if self._is_special:
2296 ans = self._check_nans(context=context)
2297 if ans:
2298 return ans
2300 dup = self._fix(context)
2301 if dup._isinfinity():
2302 return dup
2304 if not dup:
2305 return _dec_from_triple(dup._sign, '0', 0)
2306 exp_max = [context.Emax, context.Etop()][context._clamp]
2307 end = len(dup._int)
2308 exp = dup._exp
2309 while dup._int[end-1] == '0' and exp < exp_max:
2310 exp += 1
2311 end -= 1
2312 return _dec_from_triple(dup._sign, dup._int[:end], exp)
2314 def quantize(self, exp, rounding=None, context=None, watchexp=True):
2315 """Quantize self so its exponent is the same as that of exp.
2317 Similar to self._rescale(exp._exp) but with error checking.
2319 exp = _convert_other(exp, raiseit=True)
2321 if context is None:
2322 context = getcontext()
2323 if rounding is None:
2324 rounding = context.rounding
2326 if self._is_special or exp._is_special:
2327 ans = self._check_nans(exp, context)
2328 if ans:
2329 return ans
2331 if exp._isinfinity() or self._isinfinity():
2332 if exp._isinfinity() and self._isinfinity():
2333 return Decimal(self) # if both are inf, it is OK
2334 return context._raise_error(InvalidOperation,
2335 'quantize with one INF')
2337 # if we're not watching exponents, do a simple rescale
2338 if not watchexp:
2339 ans = self._rescale(exp._exp, rounding)
2340 # raise Inexact and Rounded where appropriate
2341 if ans._exp > self._exp:
2342 context._raise_error(Rounded)
2343 if ans != self:
2344 context._raise_error(Inexact)
2345 return ans
2347 # exp._exp should be between Etiny and Emax
2348 if not (context.Etiny() <= exp._exp <= context.Emax):
2349 return context._raise_error(InvalidOperation,
2350 'target exponent out of bounds in quantize')
2352 if not self:
2353 ans = _dec_from_triple(self._sign, '0', exp._exp)
2354 return ans._fix(context)
2356 self_adjusted = self.adjusted()
2357 if self_adjusted > context.Emax:
2358 return context._raise_error(InvalidOperation,
2359 'exponent of quantize result too large for current context')
2360 if self_adjusted - exp._exp + 1 > context.prec:
2361 return context._raise_error(InvalidOperation,
2362 'quantize result has too many digits for current context')
2364 ans = self._rescale(exp._exp, rounding)
2365 if ans.adjusted() > context.Emax:
2366 return context._raise_error(InvalidOperation,
2367 'exponent of quantize result too large for current context')
2368 if len(ans._int) > context.prec:
2369 return context._raise_error(InvalidOperation,
2370 'quantize result has too many digits for current context')
2372 # raise appropriate flags
2373 if ans._exp > self._exp:
2374 context._raise_error(Rounded)
2375 if ans != self:
2376 context._raise_error(Inexact)
2377 if ans and ans.adjusted() < context.Emin:
2378 context._raise_error(Subnormal)
2380 # call to fix takes care of any necessary folddown
2381 ans = ans._fix(context)
2382 return ans
2384 def same_quantum(self, other):
2385 """Return True if self and other have the same exponent; otherwise
2386 return False.
2388 If either operand is a special value, the following rules are used:
2389 * return True if both operands are infinities
2390 * return True if both operands are NaNs
2391 * otherwise, return False.
2393 other = _convert_other(other, raiseit=True)
2394 if self._is_special or other._is_special:
2395 return (self.is_nan() and other.is_nan() or
2396 self.is_infinite() and other.is_infinite())
2397 return self._exp == other._exp
2399 def _rescale(self, exp, rounding):
2400 """Rescale self so that the exponent is exp, either by padding with zeros
2401 or by truncating digits, using the given rounding mode.
2403 Specials are returned without change. This operation is
2404 quiet: it raises no flags, and uses no information from the
2405 context.
2407 exp = exp to scale to (an integer)
2408 rounding = rounding mode
2410 if self._is_special:
2411 return Decimal(self)
2412 if not self:
2413 return _dec_from_triple(self._sign, '0', exp)
2415 if self._exp >= exp:
2416 # pad answer with zeros if necessary
2417 return _dec_from_triple(self._sign,
2418 self._int + '0'*(self._exp - exp), exp)
2420 # too many digits; round and lose data. If self.adjusted() <
2421 # exp-1, replace self by 10**(exp-1) before rounding
2422 digits = len(self._int) + self._exp - exp
2423 if digits < 0:
2424 self = _dec_from_triple(self._sign, '1', exp-1)
2425 digits = 0
2426 this_function = getattr(self, self._pick_rounding_function[rounding])
2427 changed = this_function(digits)
2428 coeff = self._int[:digits] or '0'
2429 if changed == 1:
2430 coeff = str(int(coeff)+1)
2431 return _dec_from_triple(self._sign, coeff, exp)
2433 def _round(self, places, rounding):
2434 """Round a nonzero, nonspecial Decimal to a fixed number of
2435 significant figures, using the given rounding mode.
2437 Infinities, NaNs and zeros are returned unaltered.
2439 This operation is quiet: it raises no flags, and uses no
2440 information from the context.
2443 if places <= 0:
2444 raise ValueError("argument should be at least 1 in _round")
2445 if self._is_special or not self:
2446 return Decimal(self)
2447 ans = self._rescale(self.adjusted()+1-places, rounding)
2448 # it can happen that the rescale alters the adjusted exponent;
2449 # for example when rounding 99.97 to 3 significant figures.
2450 # When this happens we end up with an extra 0 at the end of
2451 # the number; a second rescale fixes this.
2452 if ans.adjusted() != self.adjusted():
2453 ans = ans._rescale(ans.adjusted()+1-places, rounding)
2454 return ans
2456 def to_integral_exact(self, rounding=None, context=None):
2457 """Rounds to a nearby integer.
2459 If no rounding mode is specified, take the rounding mode from
2460 the context. This method raises the Rounded and Inexact flags
2461 when appropriate.
2463 See also: to_integral_value, which does exactly the same as
2464 this method except that it doesn't raise Inexact or Rounded.
2466 if self._is_special:
2467 ans = self._check_nans(context=context)
2468 if ans:
2469 return ans
2470 return Decimal(self)
2471 if self._exp >= 0:
2472 return Decimal(self)
2473 if not self:
2474 return _dec_from_triple(self._sign, '0', 0)
2475 if context is None:
2476 context = getcontext()
2477 if rounding is None:
2478 rounding = context.rounding
2479 context._raise_error(Rounded)
2480 ans = self._rescale(0, rounding)
2481 if ans != self:
2482 context._raise_error(Inexact)
2483 return ans
2485 def to_integral_value(self, rounding=None, context=None):
2486 """Rounds to the nearest integer, without raising inexact, rounded."""
2487 if context is None:
2488 context = getcontext()
2489 if rounding is None:
2490 rounding = context.rounding
2491 if self._is_special:
2492 ans = self._check_nans(context=context)
2493 if ans:
2494 return ans
2495 return Decimal(self)
2496 if self._exp >= 0:
2497 return Decimal(self)
2498 else:
2499 return self._rescale(0, rounding)
2501 # the method name changed, but we provide also the old one, for compatibility
2502 to_integral = to_integral_value
2504 def sqrt(self, context=None):
2505 """Return the square root of self."""
2506 if context is None:
2507 context = getcontext()
2509 if self._is_special:
2510 ans = self._check_nans(context=context)
2511 if ans:
2512 return ans
2514 if self._isinfinity() and self._sign == 0:
2515 return Decimal(self)
2517 if not self:
2518 # exponent = self._exp // 2. sqrt(-0) = -0
2519 ans = _dec_from_triple(self._sign, '0', self._exp // 2)
2520 return ans._fix(context)
2522 if self._sign == 1:
2523 return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
2525 # At this point self represents a positive number. Let p be
2526 # the desired precision and express self in the form c*100**e
2527 # with c a positive real number and e an integer, c and e
2528 # being chosen so that 100**(p-1) <= c < 100**p. Then the
2529 # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
2530 # <= sqrt(c) < 10**p, so the closest representable Decimal at
2531 # precision p is n*10**e where n = round_half_even(sqrt(c)),
2532 # the closest integer to sqrt(c) with the even integer chosen
2533 # in the case of a tie.
2535 # To ensure correct rounding in all cases, we use the
2536 # following trick: we compute the square root to an extra
2537 # place (precision p+1 instead of precision p), rounding down.
2538 # Then, if the result is inexact and its last digit is 0 or 5,
2539 # we increase the last digit to 1 or 6 respectively; if it's
2540 # exact we leave the last digit alone. Now the final round to
2541 # p places (or fewer in the case of underflow) will round
2542 # correctly and raise the appropriate flags.
2544 # use an extra digit of precision
2545 prec = context.prec+1
2547 # write argument in the form c*100**e where e = self._exp//2
2548 # is the 'ideal' exponent, to be used if the square root is
2549 # exactly representable. l is the number of 'digits' of c in
2550 # base 100, so that 100**(l-1) <= c < 100**l.
2551 op = _WorkRep(self)
2552 e = op.exp >> 1
2553 if op.exp & 1:
2554 c = op.int * 10
2555 l = (len(self._int) >> 1) + 1
2556 else:
2557 c = op.int
2558 l = len(self._int)+1 >> 1
2560 # rescale so that c has exactly prec base 100 'digits'
2561 shift = prec-l
2562 if shift >= 0:
2563 c *= 100**shift
2564 exact = True
2565 else:
2566 c, remainder = divmod(c, 100**-shift)
2567 exact = not remainder
2568 e -= shift
2570 # find n = floor(sqrt(c)) using Newton's method
2571 n = 10**prec
2572 while True:
2573 q = c//n
2574 if n <= q:
2575 break
2576 else:
2577 n = n + q >> 1
2578 exact = exact and n*n == c
2580 if exact:
2581 # result is exact; rescale to use ideal exponent e
2582 if shift >= 0:
2583 # assert n % 10**shift == 0
2584 n //= 10**shift
2585 else:
2586 n *= 10**-shift
2587 e += shift
2588 else:
2589 # result is not exact; fix last digit as described above
2590 if n % 5 == 0:
2591 n += 1
2593 ans = _dec_from_triple(0, str(n), e)
2595 # round, and fit to current context
2596 context = context._shallow_copy()
2597 rounding = context._set_rounding(ROUND_HALF_EVEN)
2598 ans = ans._fix(context)
2599 context.rounding = rounding
2601 return ans
2603 def max(self, other, context=None):
2604 """Returns the larger value.
2606 Like max(self, other) except if one is not a number, returns
2607 NaN (and signals if one is sNaN). Also rounds.
2609 other = _convert_other(other, raiseit=True)
2611 if context is None:
2612 context = getcontext()
2614 if self._is_special or other._is_special:
2615 # If one operand is a quiet NaN and the other is number, then the
2616 # number is always returned
2617 sn = self._isnan()
2618 on = other._isnan()
2619 if sn or on:
2620 if on == 1 and sn == 0:
2621 return self._fix(context)
2622 if sn == 1 and on == 0:
2623 return other._fix(context)
2624 return self._check_nans(other, context)
2626 c = self._cmp(other)
2627 if c == 0:
2628 # If both operands are finite and equal in numerical value
2629 # then an ordering is applied:
2631 # If the signs differ then max returns the operand with the
2632 # positive sign and min returns the operand with the negative sign
2634 # If the signs are the same then the exponent is used to select
2635 # the result. This is exactly the ordering used in compare_total.
2636 c = self.compare_total(other)
2638 if c == -1:
2639 ans = other
2640 else:
2641 ans = self
2643 return ans._fix(context)
2645 def min(self, other, context=None):
2646 """Returns the smaller value.
2648 Like min(self, other) except if one is not a number, returns
2649 NaN (and signals if one is sNaN). Also rounds.
2651 other = _convert_other(other, raiseit=True)
2653 if context is None:
2654 context = getcontext()
2656 if self._is_special or other._is_special:
2657 # If one operand is a quiet NaN and the other is number, then the
2658 # number is always returned
2659 sn = self._isnan()
2660 on = other._isnan()
2661 if sn or on:
2662 if on == 1 and sn == 0:
2663 return self._fix(context)
2664 if sn == 1 and on == 0:
2665 return other._fix(context)
2666 return self._check_nans(other, context)
2668 c = self._cmp(other)
2669 if c == 0:
2670 c = self.compare_total(other)
2672 if c == -1:
2673 ans = self
2674 else:
2675 ans = other
2677 return ans._fix(context)
2679 def _isinteger(self):
2680 """Returns whether self is an integer"""
2681 if self._is_special:
2682 return False
2683 if self._exp >= 0:
2684 return True
2685 rest = self._int[self._exp:]
2686 return rest == '0'*len(rest)
2688 def _iseven(self):
2689 """Returns True if self is even. Assumes self is an integer."""
2690 if not self or self._exp > 0:
2691 return True
2692 return self._int[-1+self._exp] in '02468'
2694 def adjusted(self):
2695 """Return the adjusted exponent of self"""
2696 try:
2697 return self._exp + len(self._int) - 1
2698 # If NaN or Infinity, self._exp is string
2699 except TypeError:
2700 return 0
2702 def canonical(self, context=None):
2703 """Returns the same Decimal object.
2705 As we do not have different encodings for the same number, the
2706 received object already is in its canonical form.
2708 return self
2710 def compare_signal(self, other, context=None):
2711 """Compares self to the other operand numerically.
2713 It's pretty much like compare(), but all NaNs signal, with signaling
2714 NaNs taking precedence over quiet NaNs.
2716 other = _convert_other(other, raiseit = True)
2717 ans = self._compare_check_nans(other, context)
2718 if ans:
2719 return ans
2720 return self.compare(other, context=context)
2722 def compare_total(self, other):
2723 """Compares self to other using the abstract representations.
2725 This is not like the standard compare, which use their numerical
2726 value. Note that a total ordering is defined for all possible abstract
2727 representations.
2729 # if one is negative and the other is positive, it's easy
2730 if self._sign and not other._sign:
2731 return _NegativeOne
2732 if not self._sign and other._sign:
2733 return _One
2734 sign = self._sign
2736 # let's handle both NaN types
2737 self_nan = self._isnan()
2738 other_nan = other._isnan()
2739 if self_nan or other_nan:
2740 if self_nan == other_nan:
2741 if self._int < other._int:
2742 if sign:
2743 return _One
2744 else:
2745 return _NegativeOne
2746 if self._int > other._int:
2747 if sign:
2748 return _NegativeOne
2749 else:
2750 return _One
2751 return _Zero
2753 if sign:
2754 if self_nan == 1:
2755 return _NegativeOne
2756 if other_nan == 1:
2757 return _One
2758 if self_nan == 2:
2759 return _NegativeOne
2760 if other_nan == 2:
2761 return _One
2762 else:
2763 if self_nan == 1:
2764 return _One
2765 if other_nan == 1:
2766 return _NegativeOne
2767 if self_nan == 2:
2768 return _One
2769 if other_nan == 2:
2770 return _NegativeOne
2772 if self < other:
2773 return _NegativeOne
2774 if self > other:
2775 return _One
2777 if self._exp < other._exp:
2778 if sign:
2779 return _One
2780 else:
2781 return _NegativeOne
2782 if self._exp > other._exp:
2783 if sign:
2784 return _NegativeOne
2785 else:
2786 return _One
2787 return _Zero
2790 def compare_total_mag(self, other):
2791 """Compares self to other using abstract repr., ignoring sign.
2793 Like compare_total, but with operand's sign ignored and assumed to be 0.
2795 s = self.copy_abs()
2796 o = other.copy_abs()
2797 return s.compare_total(o)
2799 def copy_abs(self):
2800 """Returns a copy with the sign set to 0. """
2801 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2803 def copy_negate(self):
2804 """Returns a copy with the sign inverted."""
2805 if self._sign:
2806 return _dec_from_triple(0, self._int, self._exp, self._is_special)
2807 else:
2808 return _dec_from_triple(1, self._int, self._exp, self._is_special)
2810 def copy_sign(self, other):
2811 """Returns self with the sign of other."""
2812 return _dec_from_triple(other._sign, self._int,
2813 self._exp, self._is_special)
2815 def exp(self, context=None):
2816 """Returns e ** self."""
2818 if context is None:
2819 context = getcontext()
2821 # exp(NaN) = NaN
2822 ans = self._check_nans(context=context)
2823 if ans:
2824 return ans
2826 # exp(-Infinity) = 0
2827 if self._isinfinity() == -1:
2828 return _Zero
2830 # exp(0) = 1
2831 if not self:
2832 return _One
2834 # exp(Infinity) = Infinity
2835 if self._isinfinity() == 1:
2836 return Decimal(self)
2838 # the result is now guaranteed to be inexact (the true
2839 # mathematical result is transcendental). There's no need to
2840 # raise Rounded and Inexact here---they'll always be raised as
2841 # a result of the call to _fix.
2842 p = context.prec
2843 adj = self.adjusted()
2845 # we only need to do any computation for quite a small range
2846 # of adjusted exponents---for example, -29 <= adj <= 10 for
2847 # the default context. For smaller exponent the result is
2848 # indistinguishable from 1 at the given precision, while for
2849 # larger exponent the result either overflows or underflows.
2850 if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
2851 # overflow
2852 ans = _dec_from_triple(0, '1', context.Emax+1)
2853 elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
2854 # underflow to 0
2855 ans = _dec_from_triple(0, '1', context.Etiny()-1)
2856 elif self._sign == 0 and adj < -p:
2857 # p+1 digits; final round will raise correct flags
2858 ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
2859 elif self._sign == 1 and adj < -p-1:
2860 # p+1 digits; final round will raise correct flags
2861 ans = _dec_from_triple(0, '9'*(p+1), -p-1)
2862 # general case
2863 else:
2864 op = _WorkRep(self)
2865 c, e = op.int, op.exp
2866 if op.sign == 1:
2867 c = -c
2869 # compute correctly rounded result: increase precision by
2870 # 3 digits at a time until we get an unambiguously
2871 # roundable result
2872 extra = 3
2873 while True:
2874 coeff, exp = _dexp(c, e, p+extra)
2875 if coeff % (5*10**(len(str(coeff))-p-1)):
2876 break
2877 extra += 3
2879 ans = _dec_from_triple(0, str(coeff), exp)
2881 # at this stage, ans should round correctly with *any*
2882 # rounding mode, not just with ROUND_HALF_EVEN
2883 context = context._shallow_copy()
2884 rounding = context._set_rounding(ROUND_HALF_EVEN)
2885 ans = ans._fix(context)
2886 context.rounding = rounding
2888 return ans
2890 def is_canonical(self):
2891 """Return True if self is canonical; otherwise return False.
2893 Currently, the encoding of a Decimal instance is always
2894 canonical, so this method returns True for any Decimal.
2896 return True
2898 def is_finite(self):
2899 """Return True if self is finite; otherwise return False.
2901 A Decimal instance is considered finite if it is neither
2902 infinite nor a NaN.
2904 return not self._is_special
2906 def is_infinite(self):
2907 """Return True if self is infinite; otherwise return False."""
2908 return self._exp == 'F'
2910 def is_nan(self):
2911 """Return True if self is a qNaN or sNaN; otherwise return False."""
2912 return self._exp in ('n', 'N')
2914 def is_normal(self, context=None):
2915 """Return True if self is a normal number; otherwise return False."""
2916 if self._is_special or not self:
2917 return False
2918 if context is None:
2919 context = getcontext()
2920 return context.Emin <= self.adjusted() <= context.Emax
2922 def is_qnan(self):
2923 """Return True if self is a quiet NaN; otherwise return False."""
2924 return self._exp == 'n'
2926 def is_signed(self):
2927 """Return True if self is negative; otherwise return False."""
2928 return self._sign == 1
2930 def is_snan(self):
2931 """Return True if self is a signaling NaN; otherwise return False."""
2932 return self._exp == 'N'
2934 def is_subnormal(self, context=None):
2935 """Return True if self is subnormal; otherwise return False."""
2936 if self._is_special or not self:
2937 return False
2938 if context is None:
2939 context = getcontext()
2940 return self.adjusted() < context.Emin
2942 def is_zero(self):
2943 """Return True if self is a zero; otherwise return False."""
2944 return not self._is_special and self._int == '0'
2946 def _ln_exp_bound(self):
2947 """Compute a lower bound for the adjusted exponent of self.ln().
2948 In other words, compute r such that self.ln() >= 10**r. Assumes
2949 that self is finite and positive and that self != 1.
2952 # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
2953 adj = self._exp + len(self._int) - 1
2954 if adj >= 1:
2955 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2956 return len(str(adj*23//10)) - 1
2957 if adj <= -2:
2958 # argument <= 0.1
2959 return len(str((-1-adj)*23//10)) - 1
2960 op = _WorkRep(self)
2961 c, e = op.int, op.exp
2962 if adj == 0:
2963 # 1 < self < 10
2964 num = str(c-10**-e)
2965 den = str(c)
2966 return len(num) - len(den) - (num < den)
2967 # adj == -1, 0.1 <= self < 1
2968 return e + len(str(10**-e - c)) - 1
2971 def ln(self, context=None):
2972 """Returns the natural (base e) logarithm of self."""
2974 if context is None:
2975 context = getcontext()
2977 # ln(NaN) = NaN
2978 ans = self._check_nans(context=context)
2979 if ans:
2980 return ans
2982 # ln(0.0) == -Infinity
2983 if not self:
2984 return _NegativeInfinity
2986 # ln(Infinity) = Infinity
2987 if self._isinfinity() == 1:
2988 return _Infinity
2990 # ln(1.0) == 0.0
2991 if self == _One:
2992 return _Zero
2994 # ln(negative) raises InvalidOperation
2995 if self._sign == 1:
2996 return context._raise_error(InvalidOperation,
2997 'ln of a negative value')
2999 # result is irrational, so necessarily inexact
3000 op = _WorkRep(self)
3001 c, e = op.int, op.exp
3002 p = context.prec
3004 # correctly rounded result: repeatedly increase precision by 3
3005 # until we get an unambiguously roundable result
3006 places = p - self._ln_exp_bound() + 2 # at least p+3 places
3007 while True:
3008 coeff = _dlog(c, e, places)
3009 # assert len(str(abs(coeff)))-p >= 1
3010 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3011 break
3012 places += 3
3013 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3015 context = context._shallow_copy()
3016 rounding = context._set_rounding(ROUND_HALF_EVEN)
3017 ans = ans._fix(context)
3018 context.rounding = rounding
3019 return ans
3021 def _log10_exp_bound(self):
3022 """Compute a lower bound for the adjusted exponent of self.log10().
3023 In other words, find r such that self.log10() >= 10**r.
3024 Assumes that self is finite and positive and that self != 1.
3027 # For x >= 10 or x < 0.1 we only need a bound on the integer
3028 # part of log10(self), and this comes directly from the
3029 # exponent of x. For 0.1 <= x <= 10 we use the inequalities
3030 # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
3031 # (1-1/x)/2.31 > 0. If x < 1 then |log10(x)| > (1-x)/2.31 > 0
3033 adj = self._exp + len(self._int) - 1
3034 if adj >= 1:
3035 # self >= 10
3036 return len(str(adj))-1
3037 if adj <= -2:
3038 # self < 0.1
3039 return len(str(-1-adj))-1
3040 op = _WorkRep(self)
3041 c, e = op.int, op.exp
3042 if adj == 0:
3043 # 1 < self < 10
3044 num = str(c-10**-e)
3045 den = str(231*c)
3046 return len(num) - len(den) - (num < den) + 2
3047 # adj == -1, 0.1 <= self < 1
3048 num = str(10**-e-c)
3049 return len(num) + e - (num < "231") - 1
3051 def log10(self, context=None):
3052 """Returns the base 10 logarithm of self."""
3054 if context is None:
3055 context = getcontext()
3057 # log10(NaN) = NaN
3058 ans = self._check_nans(context=context)
3059 if ans:
3060 return ans
3062 # log10(0.0) == -Infinity
3063 if not self:
3064 return _NegativeInfinity
3066 # log10(Infinity) = Infinity
3067 if self._isinfinity() == 1:
3068 return _Infinity
3070 # log10(negative or -Infinity) raises InvalidOperation
3071 if self._sign == 1:
3072 return context._raise_error(InvalidOperation,
3073 'log10 of a negative value')
3075 # log10(10**n) = n
3076 if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
3077 # answer may need rounding
3078 ans = Decimal(self._exp + len(self._int) - 1)
3079 else:
3080 # result is irrational, so necessarily inexact
3081 op = _WorkRep(self)
3082 c, e = op.int, op.exp
3083 p = context.prec
3085 # correctly rounded result: repeatedly increase precision
3086 # until result is unambiguously roundable
3087 places = p-self._log10_exp_bound()+2
3088 while True:
3089 coeff = _dlog10(c, e, places)
3090 # assert len(str(abs(coeff)))-p >= 1
3091 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
3092 break
3093 places += 3
3094 ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
3096 context = context._shallow_copy()
3097 rounding = context._set_rounding(ROUND_HALF_EVEN)
3098 ans = ans._fix(context)
3099 context.rounding = rounding
3100 return ans
3102 def logb(self, context=None):
3103 """ Returns the exponent of the magnitude of self's MSD.
3105 The result is the integer which is the exponent of the magnitude
3106 of the most significant digit of self (as though it were truncated
3107 to a single digit while maintaining the value of that digit and
3108 without limiting the resulting exponent).
3110 # logb(NaN) = NaN
3111 ans = self._check_nans(context=context)
3112 if ans:
3113 return ans
3115 if context is None:
3116 context = getcontext()
3118 # logb(+/-Inf) = +Inf
3119 if self._isinfinity():
3120 return _Infinity
3122 # logb(0) = -Inf, DivisionByZero
3123 if not self:
3124 return context._raise_error(DivisionByZero, 'logb(0)', 1)
3126 # otherwise, simply return the adjusted exponent of self, as a
3127 # Decimal. Note that no attempt is made to fit the result
3128 # into the current context.
3129 return Decimal(self.adjusted())
3131 def _islogical(self):
3132 """Return True if self is a logical operand.
3134 For being logical, it must be a finite number with a sign of 0,
3135 an exponent of 0, and a coefficient whose digits must all be
3136 either 0 or 1.
3138 if self._sign != 0 or self._exp != 0:
3139 return False
3140 for dig in self._int:
3141 if dig not in '01':
3142 return False
3143 return True
3145 def _fill_logical(self, context, opa, opb):
3146 dif = context.prec - len(opa)
3147 if dif > 0:
3148 opa = '0'*dif + opa
3149 elif dif < 0:
3150 opa = opa[-context.prec:]
3151 dif = context.prec - len(opb)
3152 if dif > 0:
3153 opb = '0'*dif + opb
3154 elif dif < 0:
3155 opb = opb[-context.prec:]
3156 return opa, opb
3158 def logical_and(self, other, context=None):
3159 """Applies an 'and' operation between self and other's digits."""
3160 if context is None:
3161 context = getcontext()
3162 if not self._islogical() or not other._islogical():
3163 return context._raise_error(InvalidOperation)
3165 # fill to context.prec
3166 (opa, opb) = self._fill_logical(context, self._int, other._int)
3168 # make the operation, and clean starting zeroes
3169 result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
3170 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3172 def logical_invert(self, context=None):
3173 """Invert all its digits."""
3174 if context is None:
3175 context = getcontext()
3176 return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
3177 context)
3179 def logical_or(self, other, context=None):
3180 """Applies an 'or' operation between self and other's digits."""
3181 if context is None:
3182 context = getcontext()
3183 if not self._islogical() or not other._islogical():
3184 return context._raise_error(InvalidOperation)
3186 # fill to context.prec
3187 (opa, opb) = self._fill_logical(context, self._int, other._int)
3189 # make the operation, and clean starting zeroes
3190 result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
3191 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3193 def logical_xor(self, other, context=None):
3194 """Applies an 'xor' operation between self and other's digits."""
3195 if context is None:
3196 context = getcontext()
3197 if not self._islogical() or not other._islogical():
3198 return context._raise_error(InvalidOperation)
3200 # fill to context.prec
3201 (opa, opb) = self._fill_logical(context, self._int, other._int)
3203 # make the operation, and clean starting zeroes
3204 result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
3205 return _dec_from_triple(0, result.lstrip('0') or '0', 0)
3207 def max_mag(self, other, context=None):
3208 """Compares the values numerically with their sign ignored."""
3209 other = _convert_other(other, raiseit=True)
3211 if context is None:
3212 context = getcontext()
3214 if self._is_special or other._is_special:
3215 # If one operand is a quiet NaN and the other is number, then the
3216 # number is always returned
3217 sn = self._isnan()
3218 on = other._isnan()
3219 if sn or on:
3220 if on == 1 and sn == 0:
3221 return self._fix(context)
3222 if sn == 1 and on == 0:
3223 return other._fix(context)
3224 return self._check_nans(other, context)
3226 c = self.copy_abs()._cmp(other.copy_abs())
3227 if c == 0:
3228 c = self.compare_total(other)
3230 if c == -1:
3231 ans = other
3232 else:
3233 ans = self
3235 return ans._fix(context)
3237 def min_mag(self, other, context=None):
3238 """Compares the values numerically with their sign ignored."""
3239 other = _convert_other(other, raiseit=True)
3241 if context is None:
3242 context = getcontext()
3244 if self._is_special or other._is_special:
3245 # If one operand is a quiet NaN and the other is number, then the
3246 # number is always returned
3247 sn = self._isnan()
3248 on = other._isnan()
3249 if sn or on:
3250 if on == 1 and sn == 0:
3251 return self._fix(context)
3252 if sn == 1 and on == 0:
3253 return other._fix(context)
3254 return self._check_nans(other, context)
3256 c = self.copy_abs()._cmp(other.copy_abs())
3257 if c == 0:
3258 c = self.compare_total(other)
3260 if c == -1:
3261 ans = self
3262 else:
3263 ans = other
3265 return ans._fix(context)
3267 def next_minus(self, context=None):
3268 """Returns the largest representable number smaller than itself."""
3269 if context is None:
3270 context = getcontext()
3272 ans = self._check_nans(context=context)
3273 if ans:
3274 return ans
3276 if self._isinfinity() == -1:
3277 return _NegativeInfinity
3278 if self._isinfinity() == 1:
3279 return _dec_from_triple(0, '9'*context.prec, context.Etop())
3281 context = context.copy()
3282 context._set_rounding(ROUND_FLOOR)
3283 context._ignore_all_flags()
3284 new_self = self._fix(context)
3285 if new_self != self:
3286 return new_self
3287 return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
3288 context)
3290 def next_plus(self, context=None):
3291 """Returns the smallest representable number larger than itself."""
3292 if context is None:
3293 context = getcontext()
3295 ans = self._check_nans(context=context)
3296 if ans:
3297 return ans
3299 if self._isinfinity() == 1:
3300 return _Infinity
3301 if self._isinfinity() == -1:
3302 return _dec_from_triple(1, '9'*context.prec, context.Etop())
3304 context = context.copy()
3305 context._set_rounding(ROUND_CEILING)
3306 context._ignore_all_flags()
3307 new_self = self._fix(context)
3308 if new_self != self:
3309 return new_self
3310 return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
3311 context)
3313 def next_toward(self, other, context=None):
3314 """Returns the number closest to self, in the direction towards other.
3316 The result is the closest representable number to self
3317 (excluding self) that is in the direction towards other,
3318 unless both have the same value. If the two operands are
3319 numerically equal, then the result is a copy of self with the
3320 sign set to be the same as the sign of other.
3322 other = _convert_other(other, raiseit=True)
3324 if context is None:
3325 context = getcontext()
3327 ans = self._check_nans(other, context)
3328 if ans:
3329 return ans
3331 comparison = self._cmp(other)
3332 if comparison == 0:
3333 return self.copy_sign(other)
3335 if comparison == -1:
3336 ans = self.next_plus(context)
3337 else: # comparison == 1
3338 ans = self.next_minus(context)
3340 # decide which flags to raise using value of ans
3341 if ans._isinfinity():
3342 context._raise_error(Overflow,
3343 'Infinite result from next_toward',
3344 ans._sign)
3345 context._raise_error(Rounded)
3346 context._raise_error(Inexact)
3347 elif ans.adjusted() < context.Emin:
3348 context._raise_error(Underflow)
3349 context._raise_error(Subnormal)
3350 context._raise_error(Rounded)
3351 context._raise_error(Inexact)
3352 # if precision == 1 then we don't raise Clamped for a
3353 # result 0E-Etiny.
3354 if not ans:
3355 context._raise_error(Clamped)
3357 return ans
3359 def number_class(self, context=None):
3360 """Returns an indication of the class of self.
3362 The class is one of the following strings:
3363 sNaN
3365 -Infinity
3366 -Normal
3367 -Subnormal
3368 -Zero
3369 +Zero
3370 +Subnormal
3371 +Normal
3372 +Infinity
3374 if self.is_snan():
3375 return "sNaN"
3376 if self.is_qnan():
3377 return "NaN"
3378 inf = self._isinfinity()
3379 if inf == 1:
3380 return "+Infinity"
3381 if inf == -1:
3382 return "-Infinity"
3383 if self.is_zero():
3384 if self._sign:
3385 return "-Zero"
3386 else:
3387 return "+Zero"
3388 if context is None:
3389 context = getcontext()
3390 if self.is_subnormal(context=context):
3391 if self._sign:
3392 return "-Subnormal"
3393 else:
3394 return "+Subnormal"
3395 # just a normal, regular, boring number, :)
3396 if self._sign:
3397 return "-Normal"
3398 else:
3399 return "+Normal"
3401 def radix(self):
3402 """Just returns 10, as this is Decimal, :)"""
3403 return Decimal(10)
3405 def rotate(self, other, context=None):
3406 """Returns a rotated copy of self, value-of-other times."""
3407 if context is None:
3408 context = getcontext()
3410 ans = self._check_nans(other, context)
3411 if ans:
3412 return ans
3414 if other._exp != 0:
3415 return context._raise_error(InvalidOperation)
3416 if not (-context.prec <= int(other) <= context.prec):
3417 return context._raise_error(InvalidOperation)
3419 if self._isinfinity():
3420 return Decimal(self)
3422 # get values, pad if necessary
3423 torot = int(other)
3424 rotdig = self._int
3425 topad = context.prec - len(rotdig)
3426 if topad:
3427 rotdig = '0'*topad + rotdig
3429 # let's rotate!
3430 rotated = rotdig[torot:] + rotdig[:torot]
3431 return _dec_from_triple(self._sign,
3432 rotated.lstrip('0') or '0', self._exp)
3434 def scaleb (self, other, context=None):
3435 """Returns self operand after adding the second value to its exp."""
3436 if context is None:
3437 context = getcontext()
3439 ans = self._check_nans(other, context)
3440 if ans:
3441 return ans
3443 if other._exp != 0:
3444 return context._raise_error(InvalidOperation)
3445 liminf = -2 * (context.Emax + context.prec)
3446 limsup = 2 * (context.Emax + context.prec)
3447 if not (liminf <= int(other) <= limsup):
3448 return context._raise_error(InvalidOperation)
3450 if self._isinfinity():
3451 return Decimal(self)
3453 d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
3454 d = d._fix(context)
3455 return d
3457 def shift(self, other, context=None):
3458 """Returns a shifted copy of self, value-of-other times."""
3459 if context is None:
3460 context = getcontext()
3462 ans = self._check_nans(other, context)
3463 if ans:
3464 return ans
3466 if other._exp != 0:
3467 return context._raise_error(InvalidOperation)
3468 if not (-context.prec <= int(other) <= context.prec):
3469 return context._raise_error(InvalidOperation)
3471 if self._isinfinity():
3472 return Decimal(self)
3474 # get values, pad if necessary
3475 torot = int(other)
3476 if not torot:
3477 return Decimal(self)
3478 rotdig = self._int
3479 topad = context.prec - len(rotdig)
3480 if topad:
3481 rotdig = '0'*topad + rotdig
3483 # let's shift!
3484 if torot < 0:
3485 rotated = rotdig[:torot]
3486 else:
3487 rotated = rotdig + '0'*torot
3488 rotated = rotated[-context.prec:]
3490 return _dec_from_triple(self._sign,
3491 rotated.lstrip('0') or '0', self._exp)
3493 # Support for pickling, copy, and deepcopy
3494 def __reduce__(self):
3495 return (self.__class__, (str(self),))
3497 def __copy__(self):
3498 if type(self) == Decimal:
3499 return self # I'm immutable; therefore I am my own clone
3500 return self.__class__(str(self))
3502 def __deepcopy__(self, memo):
3503 if type(self) == Decimal:
3504 return self # My components are also immutable
3505 return self.__class__(str(self))
3507 # PEP 3101 support. See also _parse_format_specifier and _format_align
3508 def __format__(self, specifier, context=None):
3509 """Format a Decimal instance according to the given specifier.
3511 The specifier should be a standard format specifier, with the
3512 form described in PEP 3101. Formatting types 'e', 'E', 'f',
3513 'F', 'g', 'G', and '%' are supported. If the formatting type
3514 is omitted it defaults to 'g' or 'G', depending on the value
3515 of context.capitals.
3517 At this time the 'n' format specifier type (which is supposed
3518 to use the current locale) is not supported.
3521 # Note: PEP 3101 says that if the type is not present then
3522 # there should be at least one digit after the decimal point.
3523 # We take the liberty of ignoring this requirement for
3524 # Decimal---it's presumably there to make sure that
3525 # format(float, '') behaves similarly to str(float).
3526 if context is None:
3527 context = getcontext()
3529 spec = _parse_format_specifier(specifier)
3531 # special values don't care about the type or precision...
3532 if self._is_special:
3533 return _format_align(str(self), spec)
3535 # a type of None defaults to 'g' or 'G', depending on context
3536 # if type is '%', adjust exponent of self accordingly
3537 if spec['type'] is None:
3538 spec['type'] = ['g', 'G'][context.capitals]
3539 elif spec['type'] == '%':
3540 self = _dec_from_triple(self._sign, self._int, self._exp+2)
3542 # round if necessary, taking rounding mode from the context
3543 rounding = context.rounding
3544 precision = spec['precision']
3545 if precision is not None:
3546 if spec['type'] in 'eE':
3547 self = self._round(precision+1, rounding)
3548 elif spec['type'] in 'gG':
3549 if len(self._int) > precision:
3550 self = self._round(precision, rounding)
3551 elif spec['type'] in 'fF%':
3552 self = self._rescale(-precision, rounding)
3553 # special case: zeros with a positive exponent can't be
3554 # represented in fixed point; rescale them to 0e0.
3555 elif not self and self._exp > 0 and spec['type'] in 'fF%':
3556 self = self._rescale(0, rounding)
3558 # figure out placement of the decimal point
3559 leftdigits = self._exp + len(self._int)
3560 if spec['type'] in 'fF%':
3561 dotplace = leftdigits
3562 elif spec['type'] in 'eE':
3563 if not self and precision is not None:
3564 dotplace = 1 - precision
3565 else:
3566 dotplace = 1
3567 elif spec['type'] in 'gG':
3568 if self._exp <= 0 and leftdigits > -6:
3569 dotplace = leftdigits
3570 else:
3571 dotplace = 1
3573 # figure out main part of numeric string...
3574 if dotplace <= 0:
3575 num = '0.' + '0'*(-dotplace) + self._int
3576 elif dotplace >= len(self._int):
3577 # make sure we're not padding a '0' with extra zeros on the right
3578 assert dotplace==len(self._int) or self._int != '0'
3579 num = self._int + '0'*(dotplace-len(self._int))
3580 else:
3581 num = self._int[:dotplace] + '.' + self._int[dotplace:]
3583 # ...then the trailing exponent, or trailing '%'
3584 if leftdigits != dotplace or spec['type'] in 'eE':
3585 echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
3586 num = num + "{0}{1:+}".format(echar, leftdigits-dotplace)
3587 elif spec['type'] == '%':
3588 num = num + '%'
3590 # add sign
3591 if self._sign == 1:
3592 num = '-' + num
3593 return _format_align(num, spec)
3596 def _dec_from_triple(sign, coefficient, exponent, special=False):
3597 """Create a decimal instance directly, without any validation,
3598 normalization (e.g. removal of leading zeros) or argument
3599 conversion.
3601 This function is for *internal use only*.
3604 self = object.__new__(Decimal)
3605 self._sign = sign
3606 self._int = coefficient
3607 self._exp = exponent
3608 self._is_special = special
3610 return self
3612 # Register Decimal as a kind of Number (an abstract base class).
3613 # However, do not register it as Real (because Decimals are not
3614 # interoperable with floats).
3615 _numbers.Number.register(Decimal)
3618 ##### Context class #######################################################
3621 # get rounding method function:
3622 rounding_functions = [name for name in Decimal.__dict__.keys()
3623 if name.startswith('_round_')]
3624 for name in rounding_functions:
3625 # name is like _round_half_even, goes to the global ROUND_HALF_EVEN value.
3626 globalname = name[1:].upper()
3627 val = globals()[globalname]
3628 Decimal._pick_rounding_function[val] = name
3630 del name, val, globalname, rounding_functions
3632 class _ContextManager(object):
3633 """Context manager class to support localcontext().
3635 Sets a copy of the supplied context in __enter__() and restores
3636 the previous decimal context in __exit__()
3638 def __init__(self, new_context):
3639 self.new_context = new_context.copy()
3640 def __enter__(self):
3641 self.saved_context = getcontext()
3642 setcontext(self.new_context)
3643 return self.new_context
3644 def __exit__(self, t, v, tb):
3645 setcontext(self.saved_context)
3647 class Context(object):
3648 """Contains the context for a Decimal instance.
3650 Contains:
3651 prec - precision (for use in rounding, division, square roots..)
3652 rounding - rounding type (how you round)
3653 traps - If traps[exception] = 1, then the exception is
3654 raised when it is caused. Otherwise, a value is
3655 substituted in.
3656 flags - When an exception is caused, flags[exception] is set.
3657 (Whether or not the trap_enabler is set)
3658 Should be reset by user of Decimal instance.
3659 Emin - Minimum exponent
3660 Emax - Maximum exponent
3661 capitals - If 1, 1*10^1 is printed as 1E+1.
3662 If 0, printed as 1e1
3663 _clamp - If 1, change exponents if too high (Default 0)
3666 def __init__(self, prec=None, rounding=None,
3667 traps=None, flags=None,
3668 Emin=None, Emax=None,
3669 capitals=None, _clamp=0,
3670 _ignored_flags=None):
3671 if flags is None:
3672 flags = []
3673 if _ignored_flags is None:
3674 _ignored_flags = []
3675 if not isinstance(flags, dict):
3676 flags = dict([(s, int(s in flags)) for s in _signals])
3677 del s
3678 if traps is not None and not isinstance(traps, dict):
3679 traps = dict([(s, int(s in traps)) for s in _signals])
3680 del s
3681 for name, val in locals().items():
3682 if val is None:
3683 setattr(self, name, _copy.copy(getattr(DefaultContext, name)))
3684 else:
3685 setattr(self, name, val)
3686 del self.self
3688 def __repr__(self):
3689 """Show the current context."""
3690 s = []
3691 s.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3692 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
3693 % vars(self))
3694 names = [f.__name__ for f, v in self.flags.items() if v]
3695 s.append('flags=[' + ', '.join(names) + ']')
3696 names = [t.__name__ for t, v in self.traps.items() if v]
3697 s.append('traps=[' + ', '.join(names) + ']')
3698 return ', '.join(s) + ')'
3700 def clear_flags(self):
3701 """Reset all flags to zero"""
3702 for flag in self.flags:
3703 self.flags[flag] = 0
3705 def _shallow_copy(self):
3706 """Returns a shallow copy from self."""
3707 nc = Context(self.prec, self.rounding, self.traps,
3708 self.flags, self.Emin, self.Emax,
3709 self.capitals, self._clamp, self._ignored_flags)
3710 return nc
3712 def copy(self):
3713 """Returns a deep copy from self."""
3714 nc = Context(self.prec, self.rounding, self.traps.copy(),
3715 self.flags.copy(), self.Emin, self.Emax,
3716 self.capitals, self._clamp, self._ignored_flags)
3717 return nc
3718 __copy__ = copy
3720 def _raise_error(self, condition, explanation = None, *args):
3721 """Handles an error
3723 If the flag is in _ignored_flags, returns the default response.
3724 Otherwise, it sets the flag, then, if the corresponding
3725 trap_enabler is set, it reaises the exception. Otherwise, it returns
3726 the default value after setting the flag.
3728 error = _condition_map.get(condition, condition)
3729 if error in self._ignored_flags:
3730 # Don't touch the flag
3731 return error().handle(self, *args)
3733 self.flags[error] = 1
3734 if not self.traps[error]:
3735 # The errors define how to handle themselves.
3736 return condition().handle(self, *args)
3738 # Errors should only be risked on copies of the context
3739 # self._ignored_flags = []
3740 raise error(explanation)
3742 def _ignore_all_flags(self):
3743 """Ignore all flags, if they are raised"""
3744 return self._ignore_flags(*_signals)
3746 def _ignore_flags(self, *flags):
3747 """Ignore the flags, if they are raised"""
3748 # Do not mutate-- This way, copies of a context leave the original
3749 # alone.
3750 self._ignored_flags = (self._ignored_flags + list(flags))
3751 return list(flags)
3753 def _regard_flags(self, *flags):
3754 """Stop ignoring the flags, if they are raised"""
3755 if flags and isinstance(flags[0], (tuple,list)):
3756 flags = flags[0]
3757 for flag in flags:
3758 self._ignored_flags.remove(flag)
3760 # We inherit object.__hash__, so we must deny this explicitly
3761 __hash__ = None
3763 def Etiny(self):
3764 """Returns Etiny (= Emin - prec + 1)"""
3765 return int(self.Emin - self.prec + 1)
3767 def Etop(self):
3768 """Returns maximum exponent (= Emax - prec + 1)"""
3769 return int(self.Emax - self.prec + 1)
3771 def _set_rounding(self, type):
3772 """Sets the rounding type.
3774 Sets the rounding type, and returns the current (previous)
3775 rounding type. Often used like:
3777 context = context.copy()
3778 # so you don't change the calling context
3779 # if an error occurs in the middle.
3780 rounding = context._set_rounding(ROUND_UP)
3781 val = self.__sub__(other, context=context)
3782 context._set_rounding(rounding)
3784 This will make it round up for that operation.
3786 rounding = self.rounding
3787 self.rounding= type
3788 return rounding
3790 def create_decimal(self, num='0'):
3791 """Creates a new Decimal instance but using self as context.
3793 This method implements the to-number operation of the
3794 IBM Decimal specification."""
3796 if isinstance(num, basestring) and num != num.strip():
3797 return self._raise_error(ConversionSyntax,
3798 "no trailing or leading whitespace is "
3799 "permitted.")
3801 d = Decimal(num, context=self)
3802 if d._isnan() and len(d._int) > self.prec - self._clamp:
3803 return self._raise_error(ConversionSyntax,
3804 "diagnostic info too long in NaN")
3805 return d._fix(self)
3807 def create_decimal_from_float(self, f):
3808 """Creates a new Decimal instance from a float but rounding using self
3809 as the context.
3811 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3812 >>> context.create_decimal_from_float(3.1415926535897932)
3813 Decimal('3.1415')
3814 >>> context = Context(prec=5, traps=[Inexact])
3815 >>> context.create_decimal_from_float(3.1415926535897932)
3816 Traceback (most recent call last):
3818 Inexact: None
3821 d = Decimal.from_float(f) # An exact conversion
3822 return d._fix(self) # Apply the context rounding
3824 # Methods
3825 def abs(self, a):
3826 """Returns the absolute value of the operand.
3828 If the operand is negative, the result is the same as using the minus
3829 operation on the operand. Otherwise, the result is the same as using
3830 the plus operation on the operand.
3832 >>> ExtendedContext.abs(Decimal('2.1'))
3833 Decimal('2.1')
3834 >>> ExtendedContext.abs(Decimal('-100'))
3835 Decimal('100')
3836 >>> ExtendedContext.abs(Decimal('101.5'))
3837 Decimal('101.5')
3838 >>> ExtendedContext.abs(Decimal('-101.5'))
3839 Decimal('101.5')
3841 return a.__abs__(context=self)
3843 def add(self, a, b):
3844 """Return the sum of the two operands.
3846 >>> ExtendedContext.add(Decimal('12'), Decimal('7.00'))
3847 Decimal('19.00')
3848 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+4'))
3849 Decimal('1.02E+4')
3851 return a.__add__(b, context=self)
3853 def _apply(self, a):
3854 return str(a._fix(self))
3856 def canonical(self, a):
3857 """Returns the same Decimal object.
3859 As we do not have different encodings for the same number, the
3860 received object already is in its canonical form.
3862 >>> ExtendedContext.canonical(Decimal('2.50'))
3863 Decimal('2.50')
3865 return a.canonical(context=self)
3867 def compare(self, a, b):
3868 """Compares values numerically.
3870 If the signs of the operands differ, a value representing each operand
3871 ('-1' if the operand is less than zero, '0' if the operand is zero or
3872 negative zero, or '1' if the operand is greater than zero) is used in
3873 place of that operand for the comparison instead of the actual
3874 operand.
3876 The comparison is then effected by subtracting the second operand from
3877 the first and then returning a value according to the result of the
3878 subtraction: '-1' if the result is less than zero, '0' if the result is
3879 zero or negative zero, or '1' if the result is greater than zero.
3881 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('3'))
3882 Decimal('-1')
3883 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3884 Decimal('0')
3885 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3886 Decimal('0')
3887 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3888 Decimal('1')
3889 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3890 Decimal('1')
3891 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.1'))
3892 Decimal('-1')
3894 return a.compare(b, context=self)
3896 def compare_signal(self, a, b):
3897 """Compares the values of the two operands numerically.
3899 It's pretty much like compare(), but all NaNs signal, with signaling
3900 NaNs taking precedence over quiet NaNs.
3902 >>> c = ExtendedContext
3903 >>> c.compare_signal(Decimal('2.1'), Decimal('3'))
3904 Decimal('-1')
3905 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3906 Decimal('0')
3907 >>> c.flags[InvalidOperation] = 0
3908 >>> print c.flags[InvalidOperation]
3910 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3911 Decimal('NaN')
3912 >>> print c.flags[InvalidOperation]
3914 >>> c.flags[InvalidOperation] = 0
3915 >>> print c.flags[InvalidOperation]
3917 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
3918 Decimal('NaN')
3919 >>> print c.flags[InvalidOperation]
3922 return a.compare_signal(b, context=self)
3924 def compare_total(self, a, b):
3925 """Compares two operands using their abstract representation.
3927 This is not like the standard compare, which use their numerical
3928 value. Note that a total ordering is defined for all possible abstract
3929 representations.
3931 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3932 Decimal('-1')
3933 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3934 Decimal('-1')
3935 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3936 Decimal('-1')
3937 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3938 Decimal('0')
3939 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3940 Decimal('1')
3941 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
3942 Decimal('-1')
3944 return a.compare_total(b)
3946 def compare_total_mag(self, a, b):
3947 """Compares two operands using their abstract representation ignoring sign.
3949 Like compare_total, but with operand's sign ignored and assumed to be 0.
3951 return a.compare_total_mag(b)
3953 def copy_abs(self, a):
3954 """Returns a copy of the operand with the sign set to 0.
3956 >>> ExtendedContext.copy_abs(Decimal('2.1'))
3957 Decimal('2.1')
3958 >>> ExtendedContext.copy_abs(Decimal('-100'))
3959 Decimal('100')
3961 return a.copy_abs()
3963 def copy_decimal(self, a):
3964 """Returns a copy of the decimal objet.
3966 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3967 Decimal('2.1')
3968 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3969 Decimal('-1.00')
3971 return Decimal(a)
3973 def copy_negate(self, a):
3974 """Returns a copy of the operand with the sign inverted.
3976 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3977 Decimal('-101.5')
3978 >>> ExtendedContext.copy_negate(Decimal('-101.5'))
3979 Decimal('101.5')
3981 return a.copy_negate()
3983 def copy_sign(self, a, b):
3984 """Copies the second operand's sign to the first one.
3986 In detail, it returns a copy of the first operand with the sign
3987 equal to the sign of the second operand.
3989 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('7.33'))
3990 Decimal('1.50')
3991 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3992 Decimal('1.50')
3993 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3994 Decimal('-1.50')
3995 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
3996 Decimal('-1.50')
3998 return a.copy_sign(b)
4000 def divide(self, a, b):
4001 """Decimal division in a specified context.
4003 >>> ExtendedContext.divide(Decimal('1'), Decimal('3'))
4004 Decimal('0.333333333')
4005 >>> ExtendedContext.divide(Decimal('2'), Decimal('3'))
4006 Decimal('0.666666667')
4007 >>> ExtendedContext.divide(Decimal('5'), Decimal('2'))
4008 Decimal('2.5')
4009 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
4010 Decimal('0.1')
4011 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
4012 Decimal('1')
4013 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
4014 Decimal('4.00')
4015 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
4016 Decimal('1.20')
4017 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
4018 Decimal('10')
4019 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
4020 Decimal('1000')
4021 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
4022 Decimal('1.20E+6')
4024 return a.__div__(b, context=self)
4026 def divide_int(self, a, b):
4027 """Divides two numbers and returns the integer part of the result.
4029 >>> ExtendedContext.divide_int(Decimal('2'), Decimal('3'))
4030 Decimal('0')
4031 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
4032 Decimal('3')
4033 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
4034 Decimal('3')
4036 return a.__floordiv__(b, context=self)
4038 def divmod(self, a, b):
4039 return a.__divmod__(b, context=self)
4041 def exp(self, a):
4042 """Returns e ** a.
4044 >>> c = ExtendedContext.copy()
4045 >>> c.Emin = -999
4046 >>> c.Emax = 999
4047 >>> c.exp(Decimal('-Infinity'))
4048 Decimal('0')
4049 >>> c.exp(Decimal('-1'))
4050 Decimal('0.367879441')
4051 >>> c.exp(Decimal('0'))
4052 Decimal('1')
4053 >>> c.exp(Decimal('1'))
4054 Decimal('2.71828183')
4055 >>> c.exp(Decimal('0.693147181'))
4056 Decimal('2.00000000')
4057 >>> c.exp(Decimal('+Infinity'))
4058 Decimal('Infinity')
4060 return a.exp(context=self)
4062 def fma(self, a, b, c):
4063 """Returns a multiplied by b, plus c.
4065 The first two operands are multiplied together, using multiply,
4066 the third operand is then added to the result of that
4067 multiplication, using add, all with only one final rounding.
4069 >>> ExtendedContext.fma(Decimal('3'), Decimal('5'), Decimal('7'))
4070 Decimal('22')
4071 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
4072 Decimal('-8')
4073 >>> ExtendedContext.fma(Decimal('888565290'), Decimal('1557.96930'), Decimal('-86087.7578'))
4074 Decimal('1.38435736E+12')
4076 return a.fma(b, c, context=self)
4078 def is_canonical(self, a):
4079 """Return True if the operand is canonical; otherwise return False.
4081 Currently, the encoding of a Decimal instance is always
4082 canonical, so this method returns True for any Decimal.
4084 >>> ExtendedContext.is_canonical(Decimal('2.50'))
4085 True
4087 return a.is_canonical()
4089 def is_finite(self, a):
4090 """Return True if the operand is finite; otherwise return False.
4092 A Decimal instance is considered finite if it is neither
4093 infinite nor a NaN.
4095 >>> ExtendedContext.is_finite(Decimal('2.50'))
4096 True
4097 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4098 True
4099 >>> ExtendedContext.is_finite(Decimal('0'))
4100 True
4101 >>> ExtendedContext.is_finite(Decimal('Inf'))
4102 False
4103 >>> ExtendedContext.is_finite(Decimal('NaN'))
4104 False
4106 return a.is_finite()
4108 def is_infinite(self, a):
4109 """Return True if the operand is infinite; otherwise return False.
4111 >>> ExtendedContext.is_infinite(Decimal('2.50'))
4112 False
4113 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4114 True
4115 >>> ExtendedContext.is_infinite(Decimal('NaN'))
4116 False
4118 return a.is_infinite()
4120 def is_nan(self, a):
4121 """Return True if the operand is a qNaN or sNaN;
4122 otherwise return False.
4124 >>> ExtendedContext.is_nan(Decimal('2.50'))
4125 False
4126 >>> ExtendedContext.is_nan(Decimal('NaN'))
4127 True
4128 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4129 True
4131 return a.is_nan()
4133 def is_normal(self, a):
4134 """Return True if the operand is a normal number;
4135 otherwise return False.
4137 >>> c = ExtendedContext.copy()
4138 >>> c.Emin = -999
4139 >>> c.Emax = 999
4140 >>> c.is_normal(Decimal('2.50'))
4141 True
4142 >>> c.is_normal(Decimal('0.1E-999'))
4143 False
4144 >>> c.is_normal(Decimal('0.00'))
4145 False
4146 >>> c.is_normal(Decimal('-Inf'))
4147 False
4148 >>> c.is_normal(Decimal('NaN'))
4149 False
4151 return a.is_normal(context=self)
4153 def is_qnan(self, a):
4154 """Return True if the operand is a quiet NaN; otherwise return False.
4156 >>> ExtendedContext.is_qnan(Decimal('2.50'))
4157 False
4158 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4159 True
4160 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4161 False
4163 return a.is_qnan()
4165 def is_signed(self, a):
4166 """Return True if the operand is negative; otherwise return False.
4168 >>> ExtendedContext.is_signed(Decimal('2.50'))
4169 False
4170 >>> ExtendedContext.is_signed(Decimal('-12'))
4171 True
4172 >>> ExtendedContext.is_signed(Decimal('-0'))
4173 True
4175 return a.is_signed()
4177 def is_snan(self, a):
4178 """Return True if the operand is a signaling NaN;
4179 otherwise return False.
4181 >>> ExtendedContext.is_snan(Decimal('2.50'))
4182 False
4183 >>> ExtendedContext.is_snan(Decimal('NaN'))
4184 False
4185 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4186 True
4188 return a.is_snan()
4190 def is_subnormal(self, a):
4191 """Return True if the operand is subnormal; otherwise return False.
4193 >>> c = ExtendedContext.copy()
4194 >>> c.Emin = -999
4195 >>> c.Emax = 999
4196 >>> c.is_subnormal(Decimal('2.50'))
4197 False
4198 >>> c.is_subnormal(Decimal('0.1E-999'))
4199 True
4200 >>> c.is_subnormal(Decimal('0.00'))
4201 False
4202 >>> c.is_subnormal(Decimal('-Inf'))
4203 False
4204 >>> c.is_subnormal(Decimal('NaN'))
4205 False
4207 return a.is_subnormal(context=self)
4209 def is_zero(self, a):
4210 """Return True if the operand is a zero; otherwise return False.
4212 >>> ExtendedContext.is_zero(Decimal('0'))
4213 True
4214 >>> ExtendedContext.is_zero(Decimal('2.50'))
4215 False
4216 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4217 True
4219 return a.is_zero()
4221 def ln(self, a):
4222 """Returns the natural (base e) logarithm of the operand.
4224 >>> c = ExtendedContext.copy()
4225 >>> c.Emin = -999
4226 >>> c.Emax = 999
4227 >>> c.ln(Decimal('0'))
4228 Decimal('-Infinity')
4229 >>> c.ln(Decimal('1.000'))
4230 Decimal('0')
4231 >>> c.ln(Decimal('2.71828183'))
4232 Decimal('1.00000000')
4233 >>> c.ln(Decimal('10'))
4234 Decimal('2.30258509')
4235 >>> c.ln(Decimal('+Infinity'))
4236 Decimal('Infinity')
4238 return a.ln(context=self)
4240 def log10(self, a):
4241 """Returns the base 10 logarithm of the operand.
4243 >>> c = ExtendedContext.copy()
4244 >>> c.Emin = -999
4245 >>> c.Emax = 999
4246 >>> c.log10(Decimal('0'))
4247 Decimal('-Infinity')
4248 >>> c.log10(Decimal('0.001'))
4249 Decimal('-3')
4250 >>> c.log10(Decimal('1.000'))
4251 Decimal('0')
4252 >>> c.log10(Decimal('2'))
4253 Decimal('0.301029996')
4254 >>> c.log10(Decimal('10'))
4255 Decimal('1')
4256 >>> c.log10(Decimal('70'))
4257 Decimal('1.84509804')
4258 >>> c.log10(Decimal('+Infinity'))
4259 Decimal('Infinity')
4261 return a.log10(context=self)
4263 def logb(self, a):
4264 """ Returns the exponent of the magnitude of the operand's MSD.
4266 The result is the integer which is the exponent of the magnitude
4267 of the most significant digit of the operand (as though the
4268 operand were truncated to a single digit while maintaining the
4269 value of that digit and without limiting the resulting exponent).
4271 >>> ExtendedContext.logb(Decimal('250'))
4272 Decimal('2')
4273 >>> ExtendedContext.logb(Decimal('2.50'))
4274 Decimal('0')
4275 >>> ExtendedContext.logb(Decimal('0.03'))
4276 Decimal('-2')
4277 >>> ExtendedContext.logb(Decimal('0'))
4278 Decimal('-Infinity')
4280 return a.logb(context=self)
4282 def logical_and(self, a, b):
4283 """Applies the logical operation 'and' between each operand's digits.
4285 The operands must be both logical numbers.
4287 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('0'))
4288 Decimal('0')
4289 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4290 Decimal('0')
4291 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4292 Decimal('0')
4293 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4294 Decimal('1')
4295 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4296 Decimal('1000')
4297 >>> ExtendedContext.logical_and(Decimal('1111'), Decimal('10'))
4298 Decimal('10')
4300 return a.logical_and(b, context=self)
4302 def logical_invert(self, a):
4303 """Invert all the digits in the operand.
4305 The operand must be a logical number.
4307 >>> ExtendedContext.logical_invert(Decimal('0'))
4308 Decimal('111111111')
4309 >>> ExtendedContext.logical_invert(Decimal('1'))
4310 Decimal('111111110')
4311 >>> ExtendedContext.logical_invert(Decimal('111111111'))
4312 Decimal('0')
4313 >>> ExtendedContext.logical_invert(Decimal('101010101'))
4314 Decimal('10101010')
4316 return a.logical_invert(context=self)
4318 def logical_or(self, a, b):
4319 """Applies the logical operation 'or' between each operand's digits.
4321 The operands must be both logical numbers.
4323 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('0'))
4324 Decimal('0')
4325 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4326 Decimal('1')
4327 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4328 Decimal('1')
4329 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4330 Decimal('1')
4331 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4332 Decimal('1110')
4333 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
4334 Decimal('1110')
4336 return a.logical_or(b, context=self)
4338 def logical_xor(self, a, b):
4339 """Applies the logical operation 'xor' between each operand's digits.
4341 The operands must be both logical numbers.
4343 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('0'))
4344 Decimal('0')
4345 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4346 Decimal('1')
4347 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4348 Decimal('1')
4349 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4350 Decimal('0')
4351 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4352 Decimal('110')
4353 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4354 Decimal('1101')
4356 return a.logical_xor(b, context=self)
4358 def max(self, a,b):
4359 """max compares two values numerically and returns the maximum.
4361 If either operand is a NaN then the general rules apply.
4362 Otherwise, the operands are compared as though by the compare
4363 operation. If they are numerically equal then the left-hand operand
4364 is chosen as the result. Otherwise the maximum (closer to positive
4365 infinity) of the two operands is chosen as the result.
4367 >>> ExtendedContext.max(Decimal('3'), Decimal('2'))
4368 Decimal('3')
4369 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4370 Decimal('3')
4371 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4372 Decimal('1')
4373 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
4374 Decimal('7')
4376 return a.max(b, context=self)
4378 def max_mag(self, a, b):
4379 """Compares the values numerically with their sign ignored."""
4380 return a.max_mag(b, context=self)
4382 def min(self, a,b):
4383 """min compares two values numerically and returns the minimum.
4385 If either operand is a NaN then the general rules apply.
4386 Otherwise, the operands are compared as though by the compare
4387 operation. If they are numerically equal then the left-hand operand
4388 is chosen as the result. Otherwise the minimum (closer to negative
4389 infinity) of the two operands is chosen as the result.
4391 >>> ExtendedContext.min(Decimal('3'), Decimal('2'))
4392 Decimal('2')
4393 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4394 Decimal('-10')
4395 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4396 Decimal('1.0')
4397 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
4398 Decimal('7')
4400 return a.min(b, context=self)
4402 def min_mag(self, a, b):
4403 """Compares the values numerically with their sign ignored."""
4404 return a.min_mag(b, context=self)
4406 def minus(self, a):
4407 """Minus corresponds to unary prefix minus in Python.
4409 The operation is evaluated using the same rules as subtract; the
4410 operation minus(a) is calculated as subtract('0', a) where the '0'
4411 has the same exponent as the operand.
4413 >>> ExtendedContext.minus(Decimal('1.3'))
4414 Decimal('-1.3')
4415 >>> ExtendedContext.minus(Decimal('-1.3'))
4416 Decimal('1.3')
4418 return a.__neg__(context=self)
4420 def multiply(self, a, b):
4421 """multiply multiplies two operands.
4423 If either operand is a special value then the general rules apply.
4424 Otherwise, the operands are multiplied together ('long multiplication'),
4425 resulting in a number which may be as long as the sum of the lengths
4426 of the two operands.
4428 >>> ExtendedContext.multiply(Decimal('1.20'), Decimal('3'))
4429 Decimal('3.60')
4430 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4431 Decimal('21')
4432 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4433 Decimal('0.72')
4434 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-0'))
4435 Decimal('-0.0')
4436 >>> ExtendedContext.multiply(Decimal('654321'), Decimal('654321'))
4437 Decimal('4.28135971E+11')
4439 return a.__mul__(b, context=self)
4441 def next_minus(self, a):
4442 """Returns the largest representable number smaller than a.
4444 >>> c = ExtendedContext.copy()
4445 >>> c.Emin = -999
4446 >>> c.Emax = 999
4447 >>> ExtendedContext.next_minus(Decimal('1'))
4448 Decimal('0.999999999')
4449 >>> c.next_minus(Decimal('1E-1007'))
4450 Decimal('0E-1007')
4451 >>> ExtendedContext.next_minus(Decimal('-1.00000003'))
4452 Decimal('-1.00000004')
4453 >>> c.next_minus(Decimal('Infinity'))
4454 Decimal('9.99999999E+999')
4456 return a.next_minus(context=self)
4458 def next_plus(self, a):
4459 """Returns the smallest representable number larger than a.
4461 >>> c = ExtendedContext.copy()
4462 >>> c.Emin = -999
4463 >>> c.Emax = 999
4464 >>> ExtendedContext.next_plus(Decimal('1'))
4465 Decimal('1.00000001')
4466 >>> c.next_plus(Decimal('-1E-1007'))
4467 Decimal('-0E-1007')
4468 >>> ExtendedContext.next_plus(Decimal('-1.00000003'))
4469 Decimal('-1.00000002')
4470 >>> c.next_plus(Decimal('-Infinity'))
4471 Decimal('-9.99999999E+999')
4473 return a.next_plus(context=self)
4475 def next_toward(self, a, b):
4476 """Returns the number closest to a, in direction towards b.
4478 The result is the closest representable number from the first
4479 operand (but not the first operand) that is in the direction
4480 towards the second operand, unless the operands have the same
4481 value.
4483 >>> c = ExtendedContext.copy()
4484 >>> c.Emin = -999
4485 >>> c.Emax = 999
4486 >>> c.next_toward(Decimal('1'), Decimal('2'))
4487 Decimal('1.00000001')
4488 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
4489 Decimal('-0E-1007')
4490 >>> c.next_toward(Decimal('-1.00000003'), Decimal('0'))
4491 Decimal('-1.00000002')
4492 >>> c.next_toward(Decimal('1'), Decimal('0'))
4493 Decimal('0.999999999')
4494 >>> c.next_toward(Decimal('1E-1007'), Decimal('-100'))
4495 Decimal('0E-1007')
4496 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4497 Decimal('-1.00000004')
4498 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
4499 Decimal('-0.00')
4501 return a.next_toward(b, context=self)
4503 def normalize(self, a):
4504 """normalize reduces an operand to its simplest form.
4506 Essentially a plus operation with all trailing zeros removed from the
4507 result.
4509 >>> ExtendedContext.normalize(Decimal('2.1'))
4510 Decimal('2.1')
4511 >>> ExtendedContext.normalize(Decimal('-2.0'))
4512 Decimal('-2')
4513 >>> ExtendedContext.normalize(Decimal('1.200'))
4514 Decimal('1.2')
4515 >>> ExtendedContext.normalize(Decimal('-120'))
4516 Decimal('-1.2E+2')
4517 >>> ExtendedContext.normalize(Decimal('120.00'))
4518 Decimal('1.2E+2')
4519 >>> ExtendedContext.normalize(Decimal('0.00'))
4520 Decimal('0')
4522 return a.normalize(context=self)
4524 def number_class(self, a):
4525 """Returns an indication of the class of the operand.
4527 The class is one of the following strings:
4528 -sNaN
4529 -NaN
4530 -Infinity
4531 -Normal
4532 -Subnormal
4533 -Zero
4534 +Zero
4535 +Subnormal
4536 +Normal
4537 +Infinity
4539 >>> c = Context(ExtendedContext)
4540 >>> c.Emin = -999
4541 >>> c.Emax = 999
4542 >>> c.number_class(Decimal('Infinity'))
4543 '+Infinity'
4544 >>> c.number_class(Decimal('1E-10'))
4545 '+Normal'
4546 >>> c.number_class(Decimal('2.50'))
4547 '+Normal'
4548 >>> c.number_class(Decimal('0.1E-999'))
4549 '+Subnormal'
4550 >>> c.number_class(Decimal('0'))
4551 '+Zero'
4552 >>> c.number_class(Decimal('-0'))
4553 '-Zero'
4554 >>> c.number_class(Decimal('-0.1E-999'))
4555 '-Subnormal'
4556 >>> c.number_class(Decimal('-1E-10'))
4557 '-Normal'
4558 >>> c.number_class(Decimal('-2.50'))
4559 '-Normal'
4560 >>> c.number_class(Decimal('-Infinity'))
4561 '-Infinity'
4562 >>> c.number_class(Decimal('NaN'))
4563 'NaN'
4564 >>> c.number_class(Decimal('-NaN'))
4565 'NaN'
4566 >>> c.number_class(Decimal('sNaN'))
4567 'sNaN'
4569 return a.number_class(context=self)
4571 def plus(self, a):
4572 """Plus corresponds to unary prefix plus in Python.
4574 The operation is evaluated using the same rules as add; the
4575 operation plus(a) is calculated as add('0', a) where the '0'
4576 has the same exponent as the operand.
4578 >>> ExtendedContext.plus(Decimal('1.3'))
4579 Decimal('1.3')
4580 >>> ExtendedContext.plus(Decimal('-1.3'))
4581 Decimal('-1.3')
4583 return a.__pos__(context=self)
4585 def power(self, a, b, modulo=None):
4586 """Raises a to the power of b, to modulo if given.
4588 With two arguments, compute a**b. If a is negative then b
4589 must be integral. The result will be inexact unless b is
4590 integral and the result is finite and can be expressed exactly
4591 in 'precision' digits.
4593 With three arguments, compute (a**b) % modulo. For the
4594 three argument form, the following restrictions on the
4595 arguments hold:
4597 - all three arguments must be integral
4598 - b must be nonnegative
4599 - at least one of a or b must be nonzero
4600 - modulo must be nonzero and have at most 'precision' digits
4602 The result of pow(a, b, modulo) is identical to the result
4603 that would be obtained by computing (a**b) % modulo with
4604 unbounded precision, but is computed more efficiently. It is
4605 always exact.
4607 >>> c = ExtendedContext.copy()
4608 >>> c.Emin = -999
4609 >>> c.Emax = 999
4610 >>> c.power(Decimal('2'), Decimal('3'))
4611 Decimal('8')
4612 >>> c.power(Decimal('-2'), Decimal('3'))
4613 Decimal('-8')
4614 >>> c.power(Decimal('2'), Decimal('-3'))
4615 Decimal('0.125')
4616 >>> c.power(Decimal('1.7'), Decimal('8'))
4617 Decimal('69.7575744')
4618 >>> c.power(Decimal('10'), Decimal('0.301029996'))
4619 Decimal('2.00000000')
4620 >>> c.power(Decimal('Infinity'), Decimal('-1'))
4621 Decimal('0')
4622 >>> c.power(Decimal('Infinity'), Decimal('0'))
4623 Decimal('1')
4624 >>> c.power(Decimal('Infinity'), Decimal('1'))
4625 Decimal('Infinity')
4626 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4627 Decimal('-0')
4628 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4629 Decimal('1')
4630 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4631 Decimal('-Infinity')
4632 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4633 Decimal('Infinity')
4634 >>> c.power(Decimal('0'), Decimal('0'))
4635 Decimal('NaN')
4637 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4638 Decimal('11')
4639 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4640 Decimal('-11')
4641 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4642 Decimal('1')
4643 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4644 Decimal('11')
4645 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4646 Decimal('11729830')
4647 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4648 Decimal('-0')
4649 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
4650 Decimal('1')
4652 return a.__pow__(b, modulo, context=self)
4654 def quantize(self, a, b):
4655 """Returns a value equal to 'a' (rounded), having the exponent of 'b'.
4657 The coefficient of the result is derived from that of the left-hand
4658 operand. It may be rounded using the current rounding setting (if the
4659 exponent is being increased), multiplied by a positive power of ten (if
4660 the exponent is being decreased), or is unchanged (if the exponent is
4661 already equal to that of the right-hand operand).
4663 Unlike other operations, if the length of the coefficient after the
4664 quantize operation would be greater than precision then an Invalid
4665 operation condition is raised. This guarantees that, unless there is
4666 an error condition, the exponent of the result of a quantize is always
4667 equal to that of the right-hand operand.
4669 Also unlike other operations, quantize will never raise Underflow, even
4670 if the result is subnormal and inexact.
4672 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.001'))
4673 Decimal('2.170')
4674 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4675 Decimal('2.17')
4676 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4677 Decimal('2.2')
4678 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4679 Decimal('2')
4680 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4681 Decimal('0E+1')
4682 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4683 Decimal('-Infinity')
4684 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4685 Decimal('NaN')
4686 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4687 Decimal('-0')
4688 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4689 Decimal('-0E+5')
4690 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4691 Decimal('NaN')
4692 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4693 Decimal('NaN')
4694 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4695 Decimal('217.0')
4696 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4697 Decimal('217')
4698 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4699 Decimal('2.2E+2')
4700 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4701 Decimal('2E+2')
4703 return a.quantize(b, context=self)
4705 def radix(self):
4706 """Just returns 10, as this is Decimal, :)
4708 >>> ExtendedContext.radix()
4709 Decimal('10')
4711 return Decimal(10)
4713 def remainder(self, a, b):
4714 """Returns the remainder from integer division.
4716 The result is the residue of the dividend after the operation of
4717 calculating integer division as described for divide-integer, rounded
4718 to precision digits if necessary. The sign of the result, if
4719 non-zero, is the same as that of the original dividend.
4721 This operation will fail under the same conditions as integer division
4722 (that is, if integer division on the same two operands would fail, the
4723 remainder cannot be calculated).
4725 >>> ExtendedContext.remainder(Decimal('2.1'), Decimal('3'))
4726 Decimal('2.1')
4727 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4728 Decimal('1')
4729 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4730 Decimal('-1')
4731 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4732 Decimal('0.2')
4733 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4734 Decimal('0.1')
4735 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
4736 Decimal('1.0')
4738 return a.__mod__(b, context=self)
4740 def remainder_near(self, a, b):
4741 """Returns to be "a - b * n", where n is the integer nearest the exact
4742 value of "x / b" (if two integers are equally near then the even one
4743 is chosen). If the result is equal to 0 then its sign will be the
4744 sign of a.
4746 This operation will fail under the same conditions as integer division
4747 (that is, if integer division on the same two operands would fail, the
4748 remainder cannot be calculated).
4750 >>> ExtendedContext.remainder_near(Decimal('2.1'), Decimal('3'))
4751 Decimal('-0.9')
4752 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4753 Decimal('-2')
4754 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4755 Decimal('1')
4756 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4757 Decimal('-1')
4758 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4759 Decimal('0.2')
4760 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4761 Decimal('0.1')
4762 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.3'))
4763 Decimal('-0.3')
4765 return a.remainder_near(b, context=self)
4767 def rotate(self, a, b):
4768 """Returns a rotated copy of a, b times.
4770 The coefficient of the result is a rotated copy of the digits in
4771 the coefficient of the first operand. The number of places of
4772 rotation is taken from the absolute value of the second operand,
4773 with the rotation being to the left if the second operand is
4774 positive or to the right otherwise.
4776 >>> ExtendedContext.rotate(Decimal('34'), Decimal('8'))
4777 Decimal('400000003')
4778 >>> ExtendedContext.rotate(Decimal('12'), Decimal('9'))
4779 Decimal('12')
4780 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('-2'))
4781 Decimal('891234567')
4782 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('0'))
4783 Decimal('123456789')
4784 >>> ExtendedContext.rotate(Decimal('123456789'), Decimal('+2'))
4785 Decimal('345678912')
4787 return a.rotate(b, context=self)
4789 def same_quantum(self, a, b):
4790 """Returns True if the two operands have the same exponent.
4792 The result is never affected by either the sign or the coefficient of
4793 either operand.
4795 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4796 False
4797 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4798 True
4799 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4800 False
4801 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
4802 True
4804 return a.same_quantum(b)
4806 def scaleb (self, a, b):
4807 """Returns the first operand after adding the second value its exp.
4809 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('-2'))
4810 Decimal('0.0750')
4811 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4812 Decimal('7.50')
4813 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('3'))
4814 Decimal('7.50E+3')
4816 return a.scaleb (b, context=self)
4818 def shift(self, a, b):
4819 """Returns a shifted copy of a, b times.
4821 The coefficient of the result is a shifted copy of the digits
4822 in the coefficient of the first operand. The number of places
4823 to shift is taken from the absolute value of the second operand,
4824 with the shift being to the left if the second operand is
4825 positive or to the right otherwise. Digits shifted into the
4826 coefficient are zeros.
4828 >>> ExtendedContext.shift(Decimal('34'), Decimal('8'))
4829 Decimal('400000000')
4830 >>> ExtendedContext.shift(Decimal('12'), Decimal('9'))
4831 Decimal('0')
4832 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
4833 Decimal('1234567')
4834 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('0'))
4835 Decimal('123456789')
4836 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('+2'))
4837 Decimal('345678900')
4839 return a.shift(b, context=self)
4841 def sqrt(self, a):
4842 """Square root of a non-negative number to context precision.
4844 If the result must be inexact, it is rounded using the round-half-even
4845 algorithm.
4847 >>> ExtendedContext.sqrt(Decimal('0'))
4848 Decimal('0')
4849 >>> ExtendedContext.sqrt(Decimal('-0'))
4850 Decimal('-0')
4851 >>> ExtendedContext.sqrt(Decimal('0.39'))
4852 Decimal('0.624499800')
4853 >>> ExtendedContext.sqrt(Decimal('100'))
4854 Decimal('10')
4855 >>> ExtendedContext.sqrt(Decimal('1'))
4856 Decimal('1')
4857 >>> ExtendedContext.sqrt(Decimal('1.0'))
4858 Decimal('1.0')
4859 >>> ExtendedContext.sqrt(Decimal('1.00'))
4860 Decimal('1.0')
4861 >>> ExtendedContext.sqrt(Decimal('7'))
4862 Decimal('2.64575131')
4863 >>> ExtendedContext.sqrt(Decimal('10'))
4864 Decimal('3.16227766')
4865 >>> ExtendedContext.prec
4868 return a.sqrt(context=self)
4870 def subtract(self, a, b):
4871 """Return the difference between the two operands.
4873 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.07'))
4874 Decimal('0.23')
4875 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4876 Decimal('0.00')
4877 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
4878 Decimal('-0.77')
4880 return a.__sub__(b, context=self)
4882 def to_eng_string(self, a):
4883 """Converts a number to a string, using scientific notation.
4885 The operation is not affected by the context.
4887 return a.to_eng_string(context=self)
4889 def to_sci_string(self, a):
4890 """Converts a number to a string, using scientific notation.
4892 The operation is not affected by the context.
4894 return a.__str__(context=self)
4896 def to_integral_exact(self, a):
4897 """Rounds to an integer.
4899 When the operand has a negative exponent, the result is the same
4900 as using the quantize() operation using the given operand as the
4901 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4902 of the operand as the precision setting; Inexact and Rounded flags
4903 are allowed in this operation. The rounding mode is taken from the
4904 context.
4906 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4907 Decimal('2')
4908 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4909 Decimal('100')
4910 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4911 Decimal('100')
4912 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4913 Decimal('102')
4914 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4915 Decimal('-102')
4916 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4917 Decimal('1.0E+6')
4918 >>> ExtendedContext.to_integral_exact(Decimal('7.89E+77'))
4919 Decimal('7.89E+77')
4920 >>> ExtendedContext.to_integral_exact(Decimal('-Inf'))
4921 Decimal('-Infinity')
4923 return a.to_integral_exact(context=self)
4925 def to_integral_value(self, a):
4926 """Rounds to an integer.
4928 When the operand has a negative exponent, the result is the same
4929 as using the quantize() operation using the given operand as the
4930 left-hand-operand, 1E+0 as the right-hand-operand, and the precision
4931 of the operand as the precision setting, except that no flags will
4932 be set. The rounding mode is taken from the context.
4934 >>> ExtendedContext.to_integral_value(Decimal('2.1'))
4935 Decimal('2')
4936 >>> ExtendedContext.to_integral_value(Decimal('100'))
4937 Decimal('100')
4938 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4939 Decimal('100')
4940 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4941 Decimal('102')
4942 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4943 Decimal('-102')
4944 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4945 Decimal('1.0E+6')
4946 >>> ExtendedContext.to_integral_value(Decimal('7.89E+77'))
4947 Decimal('7.89E+77')
4948 >>> ExtendedContext.to_integral_value(Decimal('-Inf'))
4949 Decimal('-Infinity')
4951 return a.to_integral_value(context=self)
4953 # the method name changed, but we provide also the old one, for compatibility
4954 to_integral = to_integral_value
4956 class _WorkRep(object):
4957 __slots__ = ('sign','int','exp')
4958 # sign: 0 or 1
4959 # int: int or long
4960 # exp: None, int, or string
4962 def __init__(self, value=None):
4963 if value is None:
4964 self.sign = None
4965 self.int = 0
4966 self.exp = None
4967 elif isinstance(value, Decimal):
4968 self.sign = value._sign
4969 self.int = int(value._int)
4970 self.exp = value._exp
4971 else:
4972 # assert isinstance(value, tuple)
4973 self.sign = value[0]
4974 self.int = value[1]
4975 self.exp = value[2]
4977 def __repr__(self):
4978 return "(%r, %r, %r)" % (self.sign, self.int, self.exp)
4980 __str__ = __repr__
4984 def _normalize(op1, op2, prec = 0):
4985 """Normalizes op1, op2 to have the same exp and length of coefficient.
4987 Done during addition.
4989 if op1.exp < op2.exp:
4990 tmp = op2
4991 other = op1
4992 else:
4993 tmp = op1
4994 other = op2
4996 # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
4997 # Then adding 10**exp to tmp has the same effect (after rounding)
4998 # as adding any positive quantity smaller than 10**exp; similarly
4999 # for subtraction. So if other is smaller than 10**exp we replace
5000 # it with 10**exp. This avoids tmp.exp - other.exp getting too large.
5001 tmp_len = len(str(tmp.int))
5002 other_len = len(str(other.int))
5003 exp = tmp.exp + min(-1, tmp_len - prec - 2)
5004 if other_len + other.exp - 1 < exp:
5005 other.int = 1
5006 other.exp = exp
5008 tmp.int *= 10 ** (tmp.exp - other.exp)
5009 tmp.exp = other.exp
5010 return op1, op2
5012 ##### Integer arithmetic functions used by ln, log10, exp and __pow__ #####
5014 # This function from Tim Peters was taken from here:
5015 # http://mail.python.org/pipermail/python-list/1999-July/007758.html
5016 # The correction being in the function definition is for speed, and
5017 # the whole function is not resolved with math.log because of avoiding
5018 # the use of floats.
5019 def _nbits(n, correction = {
5020 '0': 4, '1': 3, '2': 2, '3': 2,
5021 '4': 1, '5': 1, '6': 1, '7': 1,
5022 '8': 0, '9': 0, 'a': 0, 'b': 0,
5023 'c': 0, 'd': 0, 'e': 0, 'f': 0}):
5024 """Number of bits in binary representation of the positive integer n,
5025 or 0 if n == 0.
5027 if n < 0:
5028 raise ValueError("The argument to _nbits should be nonnegative.")
5029 hex_n = "%x" % n
5030 return 4*len(hex_n) - correction[hex_n[0]]
5032 def _sqrt_nearest(n, a):
5033 """Closest integer to the square root of the positive integer n. a is
5034 an initial approximation to the square root. Any positive integer
5035 will do for a, but the closer a is to the square root of n the
5036 faster convergence will be.
5039 if n <= 0 or a <= 0:
5040 raise ValueError("Both arguments to _sqrt_nearest should be positive.")
5043 while a != b:
5044 b, a = a, a--n//a>>1
5045 return a
5047 def _rshift_nearest(x, shift):
5048 """Given an integer x and a nonnegative integer shift, return closest
5049 integer to x / 2**shift; use round-to-even in case of a tie.
5052 b, q = 1L << shift, x >> shift
5053 return q + (2*(x & (b-1)) + (q&1) > b)
5055 def _div_nearest(a, b):
5056 """Closest integer to a/b, a and b positive integers; rounds to even
5057 in the case of a tie.
5060 q, r = divmod(a, b)
5061 return q + (2*r + (q&1) > b)
5063 def _ilog(x, M, L = 8):
5064 """Integer approximation to M*log(x/M), with absolute error boundable
5065 in terms only of x/M.
5067 Given positive integers x and M, return an integer approximation to
5068 M * log(x/M). For L = 8 and 0.1 <= x/M <= 10 the difference
5069 between the approximation and the exact result is at most 22. For
5070 L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15. In
5071 both cases these are upper bounds on the error; it will usually be
5072 much smaller."""
5074 # The basic algorithm is the following: let log1p be the function
5075 # log1p(x) = log(1+x). Then log(x/M) = log1p((x-M)/M). We use
5076 # the reduction
5078 # log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
5080 # repeatedly until the argument to log1p is small (< 2**-L in
5081 # absolute value). For small y we can use the Taylor series
5082 # expansion
5084 # log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
5086 # truncating at T such that y**T is small enough. The whole
5087 # computation is carried out in a form of fixed-point arithmetic,
5088 # with a real number z being represented by an integer
5089 # approximation to z*M. To avoid loss of precision, the y below
5090 # is actually an integer approximation to 2**R*y*M, where R is the
5091 # number of reductions performed so far.
5093 y = x-M
5094 # argument reduction; R = number of reductions performed
5095 R = 0
5096 while (R <= L and long(abs(y)) << L-R >= M or
5097 R > L and abs(y) >> R-L >= M):
5098 y = _div_nearest(long(M*y) << 1,
5099 M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
5100 R += 1
5102 # Taylor series with T terms
5103 T = -int(-10*len(str(M))//(3*L))
5104 yshift = _rshift_nearest(y, R)
5105 w = _div_nearest(M, T)
5106 for k in xrange(T-1, 0, -1):
5107 w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
5109 return _div_nearest(w*y, M)
5111 def _dlog10(c, e, p):
5112 """Given integers c, e and p with c > 0, p >= 0, compute an integer
5113 approximation to 10**p * log10(c*10**e), with an absolute error of
5114 at most 1. Assumes that c*10**e is not exactly 1."""
5116 # increase precision by 2; compensate for this by dividing
5117 # final result by 100
5118 p += 2
5120 # write c*10**e as d*10**f with either:
5121 # f >= 0 and 1 <= d <= 10, or
5122 # f <= 0 and 0.1 <= d <= 1.
5123 # Thus for c*10**e close to 1, f = 0
5124 l = len(str(c))
5125 f = e+l - (e+l >= 1)
5127 if p > 0:
5128 M = 10**p
5129 k = e+p-f
5130 if k >= 0:
5131 c *= 10**k
5132 else:
5133 c = _div_nearest(c, 10**-k)
5135 log_d = _ilog(c, M) # error < 5 + 22 = 27
5136 log_10 = _log10_digits(p) # error < 1
5137 log_d = _div_nearest(log_d*M, log_10)
5138 log_tenpower = f*M # exact
5139 else:
5140 log_d = 0 # error < 2.31
5141 log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
5143 return _div_nearest(log_tenpower+log_d, 100)
5145 def _dlog(c, e, p):
5146 """Given integers c, e and p with c > 0, compute an integer
5147 approximation to 10**p * log(c*10**e), with an absolute error of
5148 at most 1. Assumes that c*10**e is not exactly 1."""
5150 # Increase precision by 2. The precision increase is compensated
5151 # for at the end with a division by 100.
5152 p += 2
5154 # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
5155 # or f <= 0 and 0.1 <= d <= 1. Then we can compute 10**p * log(c*10**e)
5156 # as 10**p * log(d) + 10**p*f * log(10).
5157 l = len(str(c))
5158 f = e+l - (e+l >= 1)
5160 # compute approximation to 10**p*log(d), with error < 27
5161 if p > 0:
5162 k = e+p-f
5163 if k >= 0:
5164 c *= 10**k
5165 else:
5166 c = _div_nearest(c, 10**-k) # error of <= 0.5 in c
5168 # _ilog magnifies existing error in c by a factor of at most 10
5169 log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
5170 else:
5171 # p <= 0: just approximate the whole thing by 0; error < 2.31
5172 log_d = 0
5174 # compute approximation to f*10**p*log(10), with error < 11.
5175 if f:
5176 extra = len(str(abs(f)))-1
5177 if p + extra >= 0:
5178 # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
5179 # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
5180 f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
5181 else:
5182 f_log_ten = 0
5183 else:
5184 f_log_ten = 0
5186 # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
5187 return _div_nearest(f_log_ten + log_d, 100)
5189 class _Log10Memoize(object):
5190 """Class to compute, store, and allow retrieval of, digits of the
5191 constant log(10) = 2.302585.... This constant is needed by
5192 Decimal.ln, Decimal.log10, Decimal.exp and Decimal.__pow__."""
5193 def __init__(self):
5194 self.digits = "23025850929940456840179914546843642076011014886"
5196 def getdigits(self, p):
5197 """Given an integer p >= 0, return floor(10**p)*log(10).
5199 For example, self.getdigits(3) returns 2302.
5201 # digits are stored as a string, for quick conversion to
5202 # integer in the case that we've already computed enough
5203 # digits; the stored digits should always be correct
5204 # (truncated, not rounded to nearest).
5205 if p < 0:
5206 raise ValueError("p should be nonnegative")
5208 if p >= len(self.digits):
5209 # compute p+3, p+6, p+9, ... digits; continue until at
5210 # least one of the extra digits is nonzero
5211 extra = 3
5212 while True:
5213 # compute p+extra digits, correct to within 1ulp
5214 M = 10**(p+extra+2)
5215 digits = str(_div_nearest(_ilog(10*M, M), 100))
5216 if digits[-extra:] != '0'*extra:
5217 break
5218 extra += 3
5219 # keep all reliable digits so far; remove trailing zeros
5220 # and next nonzero digit
5221 self.digits = digits.rstrip('0')[:-1]
5222 return int(self.digits[:p+1])
5224 _log10_digits = _Log10Memoize().getdigits
5226 def _iexp(x, M, L=8):
5227 """Given integers x and M, M > 0, such that x/M is small in absolute
5228 value, compute an integer approximation to M*exp(x/M). For 0 <=
5229 x/M <= 2.4, the absolute error in the result is bounded by 60 (and
5230 is usually much smaller)."""
5232 # Algorithm: to compute exp(z) for a real number z, first divide z
5233 # by a suitable power R of 2 so that |z/2**R| < 2**-L. Then
5234 # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
5235 # series
5237 # expm1(x) = x + x**2/2! + x**3/3! + ...
5239 # Now use the identity
5241 # expm1(2x) = expm1(x)*(expm1(x)+2)
5243 # R times to compute the sequence expm1(z/2**R),
5244 # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
5246 # Find R such that x/2**R/M <= 2**-L
5247 R = _nbits((long(x)<<L)//M)
5249 # Taylor series. (2**L)**T > M
5250 T = -int(-10*len(str(M))//(3*L))
5251 y = _div_nearest(x, T)
5252 Mshift = long(M)<<R
5253 for i in xrange(T-1, 0, -1):
5254 y = _div_nearest(x*(Mshift + y), Mshift * i)
5256 # Expansion
5257 for k in xrange(R-1, -1, -1):
5258 Mshift = long(M)<<(k+2)
5259 y = _div_nearest(y*(y+Mshift), Mshift)
5261 return M+y
5263 def _dexp(c, e, p):
5264 """Compute an approximation to exp(c*10**e), with p decimal places of
5265 precision.
5267 Returns integers d, f such that:
5269 10**(p-1) <= d <= 10**p, and
5270 (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
5272 In other words, d*10**f is an approximation to exp(c*10**e) with p
5273 digits of precision, and with an error in d of at most 1. This is
5274 almost, but not quite, the same as the error being < 1ulp: when d
5275 = 10**(p-1) the error could be up to 10 ulp."""
5277 # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
5278 p += 2
5280 # compute log(10) with extra precision = adjusted exponent of c*10**e
5281 extra = max(0, e + len(str(c)) - 1)
5282 q = p + extra
5284 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5285 # rounding down
5286 shift = e+q
5287 if shift >= 0:
5288 cshift = c*10**shift
5289 else:
5290 cshift = c//10**-shift
5291 quot, rem = divmod(cshift, _log10_digits(q))
5293 # reduce remainder back to original precision
5294 rem = _div_nearest(rem, 10**extra)
5296 # error in result of _iexp < 120; error after division < 0.62
5297 return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3
5299 def _dpower(xc, xe, yc, ye, p):
5300 """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
5301 y = yc*10**ye, compute x**y. Returns a pair of integers (c, e) such that:
5303 10**(p-1) <= c <= 10**p, and
5304 (c-1)*10**e < x**y < (c+1)*10**e
5306 in other words, c*10**e is an approximation to x**y with p digits
5307 of precision, and with an error in c of at most 1. (This is
5308 almost, but not quite, the same as the error being < 1ulp: when c
5309 == 10**(p-1) we can only guarantee error < 10ulp.)
5311 We assume that: x is positive and not equal to 1, and y is nonzero.
5314 # Find b such that 10**(b-1) <= |y| <= 10**b
5315 b = len(str(abs(yc))) + ye
5317 # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
5318 lxc = _dlog(xc, xe, p+b+1)
5320 # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
5321 shift = ye-b
5322 if shift >= 0:
5323 pc = lxc*yc*10**shift
5324 else:
5325 pc = _div_nearest(lxc*yc, 10**-shift)
5327 if pc == 0:
5328 # we prefer a result that isn't exactly 1; this makes it
5329 # easier to compute a correctly rounded result in __pow__
5330 if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
5331 coeff, exp = 10**(p-1)+1, 1-p
5332 else:
5333 coeff, exp = 10**p-1, -p
5334 else:
5335 coeff, exp = _dexp(pc, -(p+1), p+1)
5336 coeff = _div_nearest(coeff, 10)
5337 exp += 1
5339 return coeff, exp
5341 def _log10_lb(c, correction = {
5342 '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
5343 '6': 23, '7': 16, '8': 10, '9': 5}):
5344 """Compute a lower bound for 100*log10(c) for a positive integer c."""
5345 if c <= 0:
5346 raise ValueError("The argument to _log10_lb should be nonnegative.")
5347 str_c = str(c)
5348 return 100*len(str_c) - correction[str_c[0]]
5350 ##### Helper Functions ####################################################
5352 def _convert_other(other, raiseit=False):
5353 """Convert other to Decimal.
5355 Verifies that it's ok to use in an implicit construction.
5357 if isinstance(other, Decimal):
5358 return other
5359 if isinstance(other, (int, long)):
5360 return Decimal(other)
5361 if raiseit:
5362 raise TypeError("Unable to convert %s to Decimal" % other)
5363 return NotImplemented
5365 ##### Setup Specific Contexts ############################################
5367 # The default context prototype used by Context()
5368 # Is mutable, so that new contexts can have different default values
5370 DefaultContext = Context(
5371 prec=28, rounding=ROUND_HALF_EVEN,
5372 traps=[DivisionByZero, Overflow, InvalidOperation],
5373 flags=[],
5374 Emax=999999999,
5375 Emin=-999999999,
5376 capitals=1
5379 # Pre-made alternate contexts offered by the specification
5380 # Don't change these; the user should be able to select these
5381 # contexts and be able to reproduce results from other implementations
5382 # of the spec.
5384 BasicContext = Context(
5385 prec=9, rounding=ROUND_HALF_UP,
5386 traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
5387 flags=[],
5390 ExtendedContext = Context(
5391 prec=9, rounding=ROUND_HALF_EVEN,
5392 traps=[],
5393 flags=[],
5397 ##### crud for parsing strings #############################################
5399 # Regular expression used for parsing numeric strings. Additional
5400 # comments:
5402 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5403 # whitespace. But note that the specification disallows whitespace in
5404 # a numeric string.
5406 # 2. For finite numbers (not infinities and NaNs) the body of the
5407 # number between the optional sign and the optional exponent must have
5408 # at least one decimal digit, possibly after the decimal point. The
5409 # lookahead expression '(?=\d|\.\d)' checks this.
5411 # As the flag UNICODE is not enabled here, we're explicitly avoiding any
5412 # other meaning for \d than the numbers [0-9].
5414 import re
5415 _parser = re.compile(r""" # A numeric string consists of:
5416 # \s*
5417 (?P<sign>[-+])? # an optional sign, followed by either...
5419 (?=[0-9]|\.[0-9]) # ...a number (with at least one digit)
5420 (?P<int>[0-9]*) # having a (possibly empty) integer part
5421 (\.(?P<frac>[0-9]*))? # followed by an optional fractional part
5422 (E(?P<exp>[-+]?[0-9]+))? # followed by an optional exponent, or...
5424 Inf(inity)? # ...an infinity, or...
5426 (?P<signal>s)? # ...an (optionally signaling)
5427 NaN # NaN
5428 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
5430 # \s*
5432 """, re.VERBOSE | re.IGNORECASE).match
5434 _all_zeros = re.compile('0*$').match
5435 _exact_half = re.compile('50*$').match
5437 ##### PEP3101 support functions ##############################################
5438 # The functions parse_format_specifier and format_align have little to do
5439 # with the Decimal class, and could potentially be reused for other pure
5440 # Python numeric classes that want to implement __format__
5442 # A format specifier for Decimal looks like:
5444 # [[fill]align][sign][0][minimumwidth][.precision][type]
5447 _parse_format_specifier_regex = re.compile(r"""\A
5449 (?P<fill>.)?
5450 (?P<align>[<>=^])
5452 (?P<sign>[-+ ])?
5453 (?P<zeropad>0)?
5454 (?P<minimumwidth>(?!0)\d+)?
5455 (?:\.(?P<precision>0|(?!0)\d+))?
5456 (?P<type>[eEfFgG%])?
5458 """, re.VERBOSE)
5460 del re
5462 def _parse_format_specifier(format_spec):
5463 """Parse and validate a format specifier.
5465 Turns a standard numeric format specifier into a dict, with the
5466 following entries:
5468 fill: fill character to pad field to minimum width
5469 align: alignment type, either '<', '>', '=' or '^'
5470 sign: either '+', '-' or ' '
5471 minimumwidth: nonnegative integer giving minimum width
5472 precision: nonnegative integer giving precision, or None
5473 type: one of the characters 'eEfFgG%', or None
5474 unicode: either True or False (always True for Python 3.x)
5477 m = _parse_format_specifier_regex.match(format_spec)
5478 if m is None:
5479 raise ValueError("Invalid format specifier: " + format_spec)
5481 # get the dictionary
5482 format_dict = m.groupdict()
5484 # defaults for fill and alignment
5485 fill = format_dict['fill']
5486 align = format_dict['align']
5487 if format_dict.pop('zeropad') is not None:
5488 # in the face of conflict, refuse the temptation to guess
5489 if fill is not None and fill != '0':
5490 raise ValueError("Fill character conflicts with '0'"
5491 " in format specifier: " + format_spec)
5492 if align is not None and align != '=':
5493 raise ValueError("Alignment conflicts with '0' in "
5494 "format specifier: " + format_spec)
5495 fill = '0'
5496 align = '='
5497 format_dict['fill'] = fill or ' '
5498 format_dict['align'] = align or '<'
5500 if format_dict['sign'] is None:
5501 format_dict['sign'] = '-'
5503 # turn minimumwidth and precision entries into integers.
5504 # minimumwidth defaults to 0; precision remains None if not given
5505 format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
5506 if format_dict['precision'] is not None:
5507 format_dict['precision'] = int(format_dict['precision'])
5509 # if format type is 'g' or 'G' then a precision of 0 makes little
5510 # sense; convert it to 1. Same if format type is unspecified.
5511 if format_dict['precision'] == 0:
5512 if format_dict['type'] in 'gG' or format_dict['type'] is None:
5513 format_dict['precision'] = 1
5515 # record whether return type should be str or unicode
5516 format_dict['unicode'] = isinstance(format_spec, unicode)
5518 return format_dict
5520 def _format_align(body, spec_dict):
5521 """Given an unpadded, non-aligned numeric string, add padding and
5522 aligment to conform with the given format specifier dictionary (as
5523 output from parse_format_specifier).
5525 It's assumed that if body is negative then it starts with '-'.
5526 Any leading sign ('-' or '+') is stripped from the body before
5527 applying the alignment and padding rules, and replaced in the
5528 appropriate position.
5531 # figure out the sign; we only examine the first character, so if
5532 # body has leading whitespace the results may be surprising.
5533 if len(body) > 0 and body[0] in '-+':
5534 sign = body[0]
5535 body = body[1:]
5536 else:
5537 sign = ''
5539 if sign != '-':
5540 if spec_dict['sign'] in ' +':
5541 sign = spec_dict['sign']
5542 else:
5543 sign = ''
5545 # how much extra space do we have to play with?
5546 minimumwidth = spec_dict['minimumwidth']
5547 fill = spec_dict['fill']
5548 padding = fill*(max(minimumwidth - (len(sign+body)), 0))
5550 align = spec_dict['align']
5551 if align == '<':
5552 result = padding + sign + body
5553 elif align == '>':
5554 result = sign + body + padding
5555 elif align == '=':
5556 result = sign + padding + body
5557 else: #align == '^'
5558 half = len(padding)//2
5559 result = padding[:half] + sign + body + padding[half:]
5561 # make sure that result is unicode if necessary
5562 if spec_dict['unicode']:
5563 result = unicode(result)
5565 return result
5567 ##### Useful Constants (internal use only) ################################
5569 # Reusable defaults
5570 _Infinity = Decimal('Inf')
5571 _NegativeInfinity = Decimal('-Inf')
5572 _NaN = Decimal('NaN')
5573 _Zero = Decimal(0)
5574 _One = Decimal(1)
5575 _NegativeOne = Decimal(-1)
5577 # _SignedInfinity[sign] is infinity w/ that sign
5578 _SignedInfinity = (_Infinity, _NegativeInfinity)
5582 if __name__ == '__main__':
5583 import doctest, sys
5584 doctest.testmod(sys.modules[__name__])