1 # Copyright (c) 2004 Python Software Foundation.
4 # Written by Eric Price <eprice at tjhsst.edu>
5 # and Facundo Batista <facundo at taniquetil.com.ar>
6 # and Raymond Hettinger <python at rcn.com>
7 # and Aahz <aahz at pobox.com>
10 # This module is currently Py2.3 compatible and should be kept that way
11 # unless a major compelling advantage arises. IOW, 2.3 compatibility is
12 # strongly preferred, but not guaranteed.
14 # Also, this module should be kept in sync with the latest updates of
15 # the IBM specification as it evolves. Those updates will be treated
16 # as bug fixes (deviation from the spec is a compatibility, usability
17 # bug) and will be backported. At this point the spec is stabilizing
18 # and the updates are becoming fewer, smaller, and less significant.
21 This is a Py2.3 implementation of decimal floating point arithmetic based on
22 the General Decimal Arithmetic Specification:
24 www2.hursley.ibm.com/decimal/decarith.html
26 and IEEE standard 854-1987:
28 www.cs.berkeley.edu/~ejr/projects/754/private/drafts/854-1987/dir.html
30 Decimal floating point has finite precision with arbitrarily large bounds.
32 The purpose of this module is to support arithmetic using familiar
33 "schoolhouse" rules and to avoid some of the tricky representation
34 issues associated with binary floating point. The package is especially
35 useful for financial applications or for contexts where users have
36 expectations that are at odds with binary floating point (for instance,
37 in binary floating point, 1.00 % 0.1 gives 0.09999999999999995 instead
38 of the expected Decimal('0.00') returned by decimal floating point).
40 Here are some examples of using the decimal module:
42 >>> from decimal import *
43 >>> setcontext(ExtendedContext)
52 >>> Decimal('123.45e12345678901234567890')
53 Decimal('1.2345E+12345678901234567892')
54 >>> Decimal('1.33') + Decimal('1.27')
56 >>> Decimal('12.34') + Decimal('3.87') - Decimal('18.41')
59 >>> print dig / Decimal(3)
61 >>> getcontext().prec = 18
62 >>> print dig / Decimal(3)
66 >>> print Decimal(3).sqrt()
68 >>> print Decimal(3) ** 123
69 4.85192780976896427E+58
70 >>> inf = Decimal(1) / Decimal(0)
73 >>> neginf = Decimal(-1) / Decimal(0)
76 >>> print neginf + inf
78 >>> print neginf * inf
82 >>> getcontext().traps[DivisionByZero] = 1
84 Traceback (most recent call last):
90 >>> c.traps[InvalidOperation] = 0
91 >>> print c.flags[InvalidOperation]
93 >>> c.divide(Decimal(0), Decimal(0))
95 >>> c.traps[InvalidOperation] = 1
96 >>> print c.flags[InvalidOperation]
98 >>> c.flags[InvalidOperation] = 0
99 >>> print c.flags[InvalidOperation]
101 >>> print c.divide(Decimal(0), Decimal(0))
102 Traceback (most recent call last):
106 InvalidOperation: 0 / 0
107 >>> print c.flags[InvalidOperation]
109 >>> c.flags[InvalidOperation] = 0
110 >>> c.traps[InvalidOperation] = 0
111 >>> print c.divide(Decimal(0), Decimal(0))
113 >>> print c.flags[InvalidOperation]
120 'Decimal', 'Context',
123 'DefaultContext', 'BasicContext', 'ExtendedContext',
126 'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
127 'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
129 # Constants for use in setting up contexts
130 'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
131 'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
133 # Functions for manipulating contexts
134 'setcontext', 'getcontext', 'localcontext'
139 import numbers
as _numbers
142 from collections
import namedtuple
as _namedtuple
143 DecimalTuple
= _namedtuple('DecimalTuple', 'sign digits exponent')
145 DecimalTuple
= lambda *args
: args
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'
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
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
):
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
205 x._rescale( non-integer )
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
):
219 ans
= _dec_from_triple(args
[0]._sign
, args
[0]._int
, 'n', True)
220 return ans
._fix
_nan
(context
)
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
):
233 class DivisionByZero(DecimalException
, ZeroDivisionError):
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
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
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
):
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
):
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
):
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
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
]
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)
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.
394 # Python was compiled without threads; create a mock object instead
396 class MockThreading(object):
397 def local(self
, sys
=sys
):
398 return sys
.modules
[__name__
]
399 threading
= MockThreading()
400 del sys
, MockThreading
405 except AttributeError:
407 # To fix reloading, force it to create a new context
408 # Old contexts have different exceptions in their dicts, making problems.
409 if hasattr(threading
.currentThread(), '__decimal_context__'):
410 del threading
.currentThread().__decimal
_context
__
412 def setcontext(context
):
413 """Set this thread's context to context."""
414 if context
in (DefaultContext
, BasicContext
, ExtendedContext
):
415 context
= context
.copy()
416 context
.clear_flags()
417 threading
.currentThread().__decimal
_context
__ = context
420 """Returns this thread's context.
422 If this thread does not yet have a context, returns
423 a new context and sets this thread's context.
424 New contexts are copies of DefaultContext.
427 return threading
.currentThread().__decimal
_context
__
428 except AttributeError:
430 threading
.currentThread().__decimal
_context
__ = context
435 local
= threading
.local()
436 if hasattr(local
, '__decimal_context__'):
437 del local
.__decimal
_context
__
439 def getcontext(_local
=local
):
440 """Returns this thread's context.
442 If this thread does not yet have a context, returns
443 a new context and sets this thread's context.
444 New contexts are copies of DefaultContext.
447 return _local
.__decimal
_context
__
448 except AttributeError:
450 _local
.__decimal
_context
__ = context
453 def setcontext(context
, _local
=local
):
454 """Set this thread's context to context."""
455 if context
in (DefaultContext
, BasicContext
, ExtendedContext
):
456 context
= context
.copy()
457 context
.clear_flags()
458 _local
.__decimal
_context
__ = context
460 del threading
, local
# Don't contaminate the namespace
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
469 with localcontext() as ctx:
471 # Rest of sin calculation algorithm
472 # uses a precision 2 greater than normal
473 return +s # Convert result to normal precision
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()
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
518 >>> Decimal((0, (3, 1, 4), -2)) # tuple (sign, digit_tuple, exponent)
520 >>> Decimal(314) # int or long
522 >>> Decimal(Decimal(314)) # another decimal instance
524 >>> Decimal(' 3.14 \\n') # leading and trailing whitespace okay
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
536 self
= object.__new
__(cls
)
539 # REs insist on real strings, so we can too.
540 if isinstance(value
, basestring
):
541 m
= _parser(value
.strip())
544 context
= getcontext()
545 return context
._raise
_error
(ConversionSyntax
,
546 "Invalid literal for Decimal: %r" % value
)
548 if m
.group('sign') == "-":
552 intpart
= m
.group('int')
553 if intpart
is not None:
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
)
561 self
._int
= str(intpart
.lstrip('0') or '0')
563 self
._is
_special
= False
565 diag
= m
.group('diag')
568 self
._int
= str(diag
.lstrip('0'))
569 if m
.group('signal'):
577 self
._is
_special
= True
581 if isinstance(value
, (int,long)):
587 self
._int
= str(abs(value
))
588 self
._is
_special
= False
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
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
607 # tuple/list conversion (possibly from as_tuple())
608 if isinstance(value
, (list,tuple)):
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]
620 # infinity: value[1] is ignored
623 self
._is
_special
= True
625 # process and validate the digits in value[1]
627 for digit
in value
[1]:
628 if isinstance(digit
, (int, long)) and 0 <= digit
<= 9:
630 if digits
or digit
!= 0:
633 raise ValueError("The second value in the tuple must "
634 "be composed of integers in the range "
636 if value
[2] in ('n', 'N'):
637 # NaN: digits form the diagnostic
638 self
._int
= ''.join(map(str, digits
))
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]))
645 self
._is
_special
= False
647 raise ValueError("The third value in the tuple must "
648 "be an integer, or one of the "
649 "strings 'F', 'n', 'N'.")
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'))
673 >>> Decimal.from_float(float('inf'))
675 >>> Decimal.from_float(-float('inf'))
677 >>> Decimal.from_float(-0.0)
681 if isinstance(f
, (int, long)): # handle integer inputs
683 if _math
.isinf(f
) or _math
.isnan(f
): # raises TypeError if not a float
685 if _math
.copysign(1.0, f
) == 1.0:
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
)
696 from_float
= classmethod(from_float
)
699 """Returns whether the number is not actually one.
713 def _isinfinity(self
):
714 """Returns whether the number is infinite
716 0 if finite or not a number
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
733 Done before operations.
736 self_is_nan
= self
._isnan
()
740 other_is_nan
= other
._isnan
()
742 if self_is_nan
or other_is_nan
:
744 context
= getcontext()
747 return context
._raise
_error
(InvalidOperation
, 'sNaN',
749 if other_is_nan
== 2:
750 return context
._raise
_error
(InvalidOperation
, 'sNaN',
753 return self
._fix
_nan
(context
)
755 return other
._fix
_nan
(context
)
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
766 Return 0 if neither operand is a NaN.
770 context
= getcontext()
772 if self
._is
_special
or other
._is
_special
:
774 return context
._raise
_error
(InvalidOperation
,
775 'comparison involving sNaN',
777 elif other
.is_snan():
778 return context
._raise
_error
(InvalidOperation
,
779 'comparison involving sNaN',
782 return context
._raise
_error
(InvalidOperation
,
783 'comparison involving NaN',
785 elif other
.is_qnan():
786 return context
._raise
_error
(InvalidOperation
,
787 'comparison involving NaN',
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
:
809 elif self_inf
< other_inf
:
814 # check for zeros; Decimal('0') == Decimal('-0')
819 return -((-1)**other
._sign
)
821 return (-1)**self
._sign
823 # If different signs, neg one is less
824 if other
._sign
< self
._sign
:
826 if self
._sign
< other
._sign
:
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
:
836 elif self_padded
< other_padded
:
837 return -(-1)**self
._sign
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:
863 if self
.is_nan() or other
.is_nan():
865 return self
._cmp
(other
) == 0
867 def __ne__(self
, other
):
868 other
= _convert_other(other
)
869 if other
is NotImplemented:
871 if self
.is_nan() or other
.is_nan():
873 return self
._cmp
(other
) != 0
875 def __lt__(self
, other
, context
=None):
876 other
= _convert_other(other
)
877 if other
is NotImplemented:
879 ans
= self
._compare
_check
_nans
(other
, context
)
882 return self
._cmp
(other
) < 0
884 def __le__(self
, other
, context
=None):
885 other
= _convert_other(other
)
886 if other
is NotImplemented:
888 ans
= self
._compare
_check
_nans
(other
, context
)
891 return self
._cmp
(other
) <= 0
893 def __gt__(self
, other
, context
=None):
894 other
= _convert_other(other
)
895 if other
is NotImplemented:
897 ans
= self
._compare
_check
_nans
(other
, context
)
900 return self
._cmp
(other
) > 0
902 def __ge__(self
, other
, context
=None):
903 other
= _convert_other(other
)
904 if other
is NotImplemented:
906 ans
= self
._compare
_check
_nans
(other
, context
)
909 return self
._cmp
(other
) >= 0
911 def compare(self
, other
, context
=None):
912 """Compares one to another.
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
)
928 return Decimal(self
._cmp
(other
))
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')).
939 raise TypeError('Cannot hash a NaN value.')
940 return hash(str(self
))
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
956 return hash((self
._sign
,
957 self
._exp
+len(self
._int
),
958 self
._int
.rstrip('0')))
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
)
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
]
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
997 # usual scientific notation: 1 digit on left of the point
999 elif self
._int
== '0':
1000 # engineering notation, zero
1001 dotplace
= (leftdigits
+ 1) % 3 - 1
1003 # engineering notation, nonzero
1004 dotplace
= (leftdigits
- 1) % 3 + 1
1008 fracpart
= '.' + '0'*(-dotplace
) + self
._int
1009 elif dotplace
>= len(self
._int
):
1010 intpart
= self
._int
+'0'*(dotplace
-len(self
._int
))
1013 intpart
= self
._int
[:dotplace
]
1014 fracpart
= '.' + self
._int
[dotplace
:]
1015 if leftdigits
== dotplace
:
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
)
1045 # -Decimal('0') is Decimal('0'), not Decimal('-0')
1046 ans
= self
.copy_abs()
1048 ans
= self
.copy_negate()
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
)
1066 ans
= self
.copy_abs()
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
1082 return self
.copy_abs()
1084 if self
._is
_special
:
1085 ans
= self
._check
_nans
(context
=context
)
1090 ans
= self
.__neg
__(context
=context
)
1092 ans
= self
.__pos
__(context
=context
)
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:
1106 context
= getcontext()
1108 if self
._is
_special
or other
._is
_special
:
1109 ans
= self
._check
_nans
(other
, context
)
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
)
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.
1127 if not self
and not other
:
1128 sign
= min(self
._sign
, other
._sign
)
1131 ans
= _dec_from_triple(sign
, '0', exp
)
1132 ans
= ans
._fix
(context
)
1135 exp
= max(exp
, other
._exp
- context
.prec
-1)
1136 ans
= other
._rescale
(exp
, context
.rounding
)
1137 ans
= ans
._fix
(context
)
1140 exp
= max(exp
, self
._exp
- context
.prec
-1)
1141 ans
= self
._rescale
(exp
, context
.rounding
)
1142 ans
= ans
._fix
(context
)
1145 op1
= _WorkRep(self
)
1146 op2
= _WorkRep(other
)
1147 op1
, op2
= _normalize(op1
, op2
, context
.prec
)
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
)
1156 if op1
.int < op2
.int:
1158 # OK, now abs(op1) > abs(op2)
1161 op1
.sign
, op2
.sign
= op2
.sign
, op1
.sign
1164 # So we know the sign, and op1 > 0.
1167 op1
.sign
, op2
.sign
= (0, 0)
1170 # Now, op1 > abs(op2) > 0
1173 result
.int = op1
.int + op2
.int
1175 result
.int = op1
.int - op2
.int
1177 result
.exp
= op1
.exp
1178 ans
= Decimal(result
)
1179 ans
= ans
._fix
(context
)
1184 def __sub__(self
, other
, context
=None):
1185 """Return self - other"""
1186 other
= _convert_other(other
)
1187 if other
is NotImplemented:
1190 if self
._is
_special
or other
._is
_special
:
1191 ans
= self
._check
_nans
(other
, context
=context
)
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:
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:
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
)
1225 if self
._isinfinity
():
1227 return context
._raise
_error
(InvalidOperation
, '(+-)INF * 0')
1228 return _SignedInfinity
[resultsign
]
1230 if other
._isinfinity
():
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
)
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
)
1249 if other
._int
== '1':
1250 ans
= _dec_from_triple(resultsign
, self
._int
, resultexp
)
1251 ans
= ans
._fix
(context
)
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
)
1263 def __truediv__(self
, other
, context
=None):
1264 """Return self / other."""
1265 other
= _convert_other(other
)
1266 if other
is NotImplemented:
1267 return NotImplemented
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
)
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
1292 return context
._raise
_error
(DivisionUndefined
, '0 / 0')
1293 return context
._raise
_error
(DivisionByZero
, 'x / 0', sign
)
1296 exp
= self
._exp
- other
._exp
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
)
1305 coeff
, remainder
= divmod(op1
.int * 10**shift
, op2
.int)
1307 coeff
, remainder
= divmod(op1
.int, op2
.int * 10**-shift
)
1309 # result is not exact; adjust to ensure correct rounding
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:
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
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
)
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')
1355 def __rtruediv__(self
, other
, context
=None):
1356 """Swaps self/other and returns __truediv__."""
1357 other
= _convert_other(other
)
1358 if other
is NotImplemented:
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:
1374 context
= getcontext()
1376 ans
= self
._check
_nans
(other
, context
)
1380 sign
= self
._sign ^ other
._sign
1381 if self
._isinfinity
():
1382 if other
._isinfinity
():
1383 ans
= context
._raise
_error
(InvalidOperation
, 'divmod(INF, INF)')
1386 return (_SignedInfinity
[sign
],
1387 context
._raise
_error
(InvalidOperation
, 'INF % x'))
1391 ans
= context
._raise
_error
(DivisionUndefined
, 'divmod(0, 0)')
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:
1406 return other
.__divmod
__(self
, context
=context
)
1408 def __mod__(self
, other
, context
=None):
1412 other
= _convert_other(other
)
1413 if other
is NotImplemented:
1417 context
= getcontext()
1419 ans
= self
._check
_nans
(other
, context
)
1423 if self
._isinfinity
():
1424 return context
._raise
_error
(InvalidOperation
, 'INF % x')
1427 return context
._raise
_error
(InvalidOperation
, 'x % 0')
1429 return context
._raise
_error
(DivisionUndefined
, '0 % 0')
1431 remainder
= self
._divide
(other
, context
)[1]
1432 remainder
= remainder
._fix
(context
)
1435 def __rmod__(self
, other
, context
=None):
1436 """Swaps self/other and returns __mod__."""
1437 other
= _convert_other(other
)
1438 if other
is NotImplemented:
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
1447 context
= getcontext()
1449 other
= _convert_other(other
, raiseit
=True)
1451 ans
= self
._check
_nans
(other
, context
)
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
1463 return context
._raise
_error
(InvalidOperation
,
1464 'remainder_near(x, 0)')
1466 return context
._raise
_error
(DivisionUndefined
,
1467 'remainder_near(0, 0)')
1469 # other = +/-infinity -> remainder = self
1470 if other
._isinfinity
():
1472 return ans
._fix
(context
)
1474 # self = 0 -> remainder = self, with ideal exponent
1475 ideal_exponent
= min(self
._exp
, other
._exp
)
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
)
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
)
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:
1505 if q
>= 10**context
.prec
:
1506 return context
._raise
_error
(DivisionImpossible
)
1508 # result has same sign as self unless r is negative
1514 ans
= _dec_from_triple(sign
, str(r
), ideal_exponent
)
1515 return ans
._fix
(context
)
1517 def __floordiv__(self
, other
, context
=None):
1519 other
= _convert_other(other
)
1520 if other
is NotImplemented:
1524 context
= getcontext()
1526 ans
= self
._check
_nans
(other
, context
)
1530 if self
._isinfinity
():
1531 if other
._isinfinity
():
1532 return context
._raise
_error
(InvalidOperation
, 'INF // INF')
1534 return _SignedInfinity
[self
._sign ^ other
._sign
]
1538 return context
._raise
_error
(DivisionByZero
, 'x // 0',
1539 self
._sign ^ other
._sign
)
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:
1550 return other
.__floordiv
__(self
, context
=context
)
1552 def __float__(self
):
1553 """Float representation."""
1554 return float(str(self
))
1557 """Converts self to an int, truncating if necessary."""
1558 if self
._is
_special
:
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
1566 return s
*int(self
._int
)*10**self
._exp
1568 return s
*int(self
._int
[:self
._exp
] or '0')
1574 real
= property(real
)
1578 imag
= property(imag
)
1580 def conjugate(self
):
1583 def __complex__(self
):
1584 return complex(float(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"""
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.
1611 self - Decimal instance
1612 context - context used.
1615 if self
._is
_special
:
1617 # decapitate payload if necessary
1618 return self
._fix
_nan
(context
)
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()
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
)
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
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
)
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
1654 self
= _dec_from_triple(self
._sign
, '1', exp_min
-1)
1656 this_function
= getattr(self
, self
._pick
_rounding
_function
[context
.rounding
])
1657 changed
= this_function(digits
)
1658 coeff
= self
._int
[:digits
] or '0'
1660 coeff
= str(int(coeff
)+1)
1661 ans
= _dec_from_triple(self
._sign
, coeff
, exp_min
)
1664 context
._raise
_error
(Inexact
)
1665 if self_is_subnormal
:
1666 context
._raise
_error
(Underflow
)
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
1674 ans
= _dec_from_triple(ans
._sign
,
1675 ans
._int
[:-1], ans
._exp
+1)
1677 # Inexact and Rounded have already been raised
1678 ans
= context
._raise
_error
(Overflow
, 'above Emax',
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
):
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':
1718 elif _all_zeros(self
._int
, prec
):
1723 def _round_half_down(self
, prec
):
1725 if _exact_half(self
._int
, prec
):
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'):
1736 return self
._round
_half
_up
(prec
)
1738 def _round_ceiling(self
, prec
):
1739 """Rounds up (not away from 0 if negative.)"""
1741 return self
._round
_down
(prec
)
1743 return -self
._round
_down
(prec
)
1745 def _round_floor(self
, prec
):
1746 """Rounds down (not towards 0 if negative)"""
1748 return self
._round
_down
(prec
)
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
)
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
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
:
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':
1783 elif other
._exp
== 'n':
1785 elif self
._exp
== 'F':
1787 return context
._raise
_error
(InvalidOperation
,
1789 product
= _SignedInfinity
[self
._sign ^ other
._sign
]
1790 elif other
._exp
== 'F':
1792 return context
._raise
_error
(InvalidOperation
,
1794 product
= _SignedInfinity
[self
._sign ^ other
._sign
]
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)
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',
1824 if other_is_nan
== 2:
1825 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1827 if modulo_is_nan
== 2:
1828 return context
._raise
_error
(InvalidOperation
, 'sNaN',
1831 return self
._fix
_nan
(context
)
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')
1844 return context
._raise
_error
(InvalidOperation
,
1845 'pow() 2nd argument cannot be '
1846 'negative when 3rd argument specified')
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 '
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
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 =
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
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
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|
1947 xc
, xe
= x
.int, x
.exp
1953 yc
, ye
= y
.int, y
.exp
1958 # case where xc == 1: result is 10**(xe*y), with xe*y
1959 # required to be an integer
1962 exponent
= xe
*yc
*10**ye
1964 exponent
, remainder
= divmod(xe
*yc
, 10**-ye
)
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)
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.
1980 last_digit
= xc
% 10
1981 if last_digit
in (2,4,6,8):
1982 # quick test for power of 2
1985 # now xc is a power of 2; e is its exponent
1987 # find e*y and xe*y; both must be integers
1989 y_as_int
= yc
*10**ye
1994 e
, remainder
= divmod(e
*yc
, ten_pow
)
1997 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
2001 if e
*65 >= p
*93: # 93/65 > log(10)/log(5)
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
)
2016 y_as_integer
= yc
*10**ye
2018 xe
= xe
*y_as_integer
2021 e
, remainder
= divmod(e
*yc
, ten_pow
)
2024 xe
, remainder
= divmod(xe
*yc
, ten_pow
)
2027 if e
*3 >= p
*10: # 10/3 > log(10)/log(2)
2036 return _dec_from_triple(0, str(xc
), xe
)
2038 # now y is positive; find m and n such that y = m/n
2042 if xe
!= 0 and len(str(abs(yc
*xe
))) <= -ye
:
2044 xc_bits
= _nbits(xc
)
2045 if xc
!= 1 and len(str(abs(yc
)*xc_bits
)) <= -ye
:
2047 m
, n
= yc
, 10**(-ye
)
2048 while m
% 2 == n
% 2 == 0:
2051 while m
% 5 == n
% 5 == 0:
2055 # compute nth root of xc*10**xe
2057 # if 1 < xc < 2**n then xc isn't an nth power
2058 if xc
!= 1 and xc_bits
<= n
:
2061 xe
, rem
= divmod(xe
, n
)
2065 # compute nth root of xc using Newton's method
2066 a
= 1L << -(-_nbits(xc
)//n
) # initial estimate
2068 q
, r
= divmod(xc
, a
**(n
-1))
2072 a
= (a
*(n
-1) + q
)//n
2073 if not (a
== q
and r
== 0):
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
):
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
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
))
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
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
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:
2132 context
= getcontext()
2134 # either argument is a NaN => result is NaN
2135 ans
= self
._check
_nans
(other
, context
)
2139 # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
2142 return context
._raise
_error
(InvalidOperation
, '0 ** 0')
2146 # result has sign 1 iff self._sign is 1 and other is an odd integer
2149 if other
._isinteger
():
2150 if not other
._iseven
():
2153 # -ve**noninteger = NaN
2154 # (-0)**noninteger = 0**noninteger
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
2163 if other
._sign
== 0:
2164 return _dec_from_triple(result_sign
, '0', 0)
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
]
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
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:
2186 elif other
> context
.prec
:
2187 multiplier
= context
.prec
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
)
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)
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.
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
._log
10_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)
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
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))
2245 xc
, xe
= x
.int, x
.exp
2247 yc
, ye
= y
.int, y
.exp
2251 # compute correctly rounded result: start with precision +3,
2252 # then increase precision until result is unambiguously roundable
2255 coeff
, exp
= _dpower(xc
, xe
, yc
, ye
, p
+extra
)
2256 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
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
,
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
)
2282 def __rpow__(self
, other
, context
=None):
2283 """Swaps self/other and returns __pow__."""
2284 other
= _convert_other(other
)
2285 if other
is NotImplemented:
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"""
2293 context
= getcontext()
2295 if self
._is
_special
:
2296 ans
= self
._check
_nans
(context
=context
)
2300 dup
= self
._fix
(context
)
2301 if dup
._isinfinity
():
2305 return _dec_from_triple(dup
._sign
, '0', 0)
2306 exp_max
= [context
.Emax
, context
.Etop()][context
._clamp
]
2309 while dup
._int
[end
-1] == '0' and exp
< exp_max
:
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)
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
)
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
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
)
2344 context
._raise
_error
(Inexact
)
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')
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
)
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
)
2384 def same_quantum(self
, other
):
2385 """Return True if self and other have the same exponent; otherwise
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
2407 exp = exp to scale to (an integer)
2408 rounding = rounding mode
2410 if self
._is
_special
:
2411 return Decimal(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
2424 self
= _dec_from_triple(self
._sign
, '1', exp
-1)
2426 this_function
= getattr(self
, self
._pick
_rounding
_function
[rounding
])
2427 changed
= this_function(digits
)
2428 coeff
= self
._int
[:digits
] or '0'
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.
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
)
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
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
)
2470 return Decimal(self
)
2472 return Decimal(self
)
2474 return _dec_from_triple(self
._sign
, '0', 0)
2476 context
= getcontext()
2477 if rounding
is None:
2478 rounding
= context
.rounding
2479 context
._raise
_error
(Rounded
)
2480 ans
= self
._rescale
(0, rounding
)
2482 context
._raise
_error
(Inexact
)
2485 def to_integral_value(self
, rounding
=None, context
=None):
2486 """Rounds to the nearest integer, without raising inexact, rounded."""
2488 context
= getcontext()
2489 if rounding
is None:
2490 rounding
= context
.rounding
2491 if self
._is
_special
:
2492 ans
= self
._check
_nans
(context
=context
)
2495 return Decimal(self
)
2497 return Decimal(self
)
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."""
2507 context
= getcontext()
2509 if self
._is
_special
:
2510 ans
= self
._check
_nans
(context
=context
)
2514 if self
._isinfinity
() and self
._sign
== 0:
2515 return Decimal(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
)
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.
2555 l
= (len(self
._int
) >> 1) + 1
2558 l
= len(self
._int
)+1 >> 1
2560 # rescale so that c has exactly prec base 100 'digits'
2566 c
, remainder
= divmod(c
, 100**-shift
)
2567 exact
= not remainder
2570 # find n = floor(sqrt(c)) using Newton's method
2578 exact
= exact
and n
*n
== c
2581 # result is exact; rescale to use ideal exponent e
2583 # assert n % 10**shift == 0
2589 # result is not exact; fix last digit as described above
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
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)
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
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
)
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
)
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)
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
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
)
2670 c
= self
.compare_total(other
)
2677 return ans
._fix
(context
)
2679 def _isinteger(self
):
2680 """Returns whether self is an integer"""
2681 if self
._is
_special
:
2685 rest
= self
._int
[self
._exp
:]
2686 return rest
== '0'*len(rest
)
2689 """Returns True if self is even. Assumes self is an integer."""
2690 if not self
or self
._exp
> 0:
2692 return self
._int
[-1+self
._exp
] in '02468'
2695 """Return the adjusted exponent of self"""
2697 return self
._exp
+ len(self
._int
) - 1
2698 # If NaN or Infinity, self._exp is string
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.
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
)
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
2729 # if one is negative and the other is positive, it's easy
2730 if self
._sign
and not other
._sign
:
2732 if not self
._sign
and other
._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
:
2746 if self
._int
> other
._int
:
2777 if self
._exp
< other
._exp
:
2782 if self
._exp
> other
._exp
:
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.
2796 o
= other
.copy_abs()
2797 return s
.compare_total(o
)
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."""
2806 return _dec_from_triple(0, self
._int
, self
._exp
, self
._is
_special
)
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."""
2819 context
= getcontext()
2822 ans
= self
._check
_nans
(context
=context
)
2826 # exp(-Infinity) = 0
2827 if self
._isinfinity
() == -1:
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.
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)):
2852 ans
= _dec_from_triple(0, '1', context
.Emax
+1)
2853 elif self
._sign
== 1 and adj
> len(str((-context
.Etiny()+1)*3)):
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)
2865 c
, e
= op
.int, op
.exp
2869 # compute correctly rounded result: increase precision by
2870 # 3 digits at a time until we get an unambiguously
2874 coeff
, exp
= _dexp(c
, e
, p
+extra
)
2875 if coeff
% (5*10**(len(str(coeff
))-p
-1)):
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
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.
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
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'
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
:
2919 context
= getcontext()
2920 return context
.Emin
<= self
.adjusted() <= context
.Emax
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
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
:
2939 context
= getcontext()
2940 return self
.adjusted() < context
.Emin
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
2955 # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
2956 return len(str(adj
*23//10)) - 1
2959 return len(str((-1-adj
)*23//10)) - 1
2961 c
, e
= op
.int, op
.exp
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."""
2975 context
= getcontext()
2978 ans
= self
._check
_nans
(context
=context
)
2982 # ln(0.0) == -Infinity
2984 return _NegativeInfinity
2986 # ln(Infinity) = Infinity
2987 if self
._isinfinity
() == 1:
2994 # ln(negative) raises InvalidOperation
2996 return context
._raise
_error
(InvalidOperation
,
2997 'ln of a negative value')
2999 # result is irrational, so necessarily inexact
3001 c
, e
= op
.int, op
.exp
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
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)):
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
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
3036 return len(str(adj
))-1
3039 return len(str(-1-adj
))-1
3041 c
, e
= op
.int, op
.exp
3046 return len(num
) - len(den
) - (num
< den
) + 2
3047 # adj == -1, 0.1 <= self < 1
3049 return len(num
) + e
- (num
< "231") - 1
3051 def log10(self
, context
=None):
3052 """Returns the base 10 logarithm of self."""
3055 context
= getcontext()
3058 ans
= self
._check
_nans
(context
=context
)
3062 # log10(0.0) == -Infinity
3064 return _NegativeInfinity
3066 # log10(Infinity) = Infinity
3067 if self
._isinfinity
() == 1:
3070 # log10(negative or -Infinity) raises InvalidOperation
3072 return context
._raise
_error
(InvalidOperation
,
3073 'log10 of a negative value')
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)
3080 # result is irrational, so necessarily inexact
3082 c
, e
= op
.int, op
.exp
3085 # correctly rounded result: repeatedly increase precision
3086 # until result is unambiguously roundable
3087 places
= p
-self
._log
10_exp
_bound
()+2
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)):
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
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).
3111 ans
= self
._check
_nans
(context
=context
)
3116 context
= getcontext()
3118 # logb(+/-Inf) = +Inf
3119 if self
._isinfinity
():
3122 # logb(0) = -Inf, DivisionByZero
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
3138 if self
._sign
!= 0 or self
._exp
!= 0:
3140 for dig
in self
._int
:
3145 def _fill_logical(self
, context
, opa
, opb
):
3146 dif
= context
.prec
- len(opa
)
3150 opa
= opa
[-context
.prec
:]
3151 dif
= context
.prec
- len(opb
)
3155 opb
= opb
[-context
.prec
:]
3158 def logical_and(self
, other
, context
=None):
3159 """Applies an 'and' operation between self and other's digits."""
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."""
3175 context
= getcontext()
3176 return self
.logical_xor(_dec_from_triple(0,'1'*context
.prec
,0),
3179 def logical_or(self
, other
, context
=None):
3180 """Applies an 'or' operation between self and other's digits."""
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."""
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)
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
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())
3228 c
= self
.compare_total(other
)
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)
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
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())
3258 c
= self
.compare_total(other
)
3265 return ans
._fix
(context
)
3267 def next_minus(self
, context
=None):
3268 """Returns the largest representable number smaller than itself."""
3270 context
= getcontext()
3272 ans
= self
._check
_nans
(context
=context
)
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
:
3287 return self
.__sub
__(_dec_from_triple(0, '1', context
.Etiny()-1),
3290 def next_plus(self
, context
=None):
3291 """Returns the smallest representable number larger than itself."""
3293 context
= getcontext()
3295 ans
= self
._check
_nans
(context
=context
)
3299 if self
._isinfinity
() == 1:
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
:
3310 return self
.__add
__(_dec_from_triple(0, '1', context
.Etiny()-1),
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)
3325 context
= getcontext()
3327 ans
= self
._check
_nans
(other
, context
)
3331 comparison
= self
._cmp
(other
)
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',
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
3355 context
._raise
_error
(Clamped
)
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:
3378 inf
= self
._isinfinity
()
3389 context
= getcontext()
3390 if self
.is_subnormal(context
=context
):
3395 # just a normal, regular, boring number, :)
3402 """Just returns 10, as this is Decimal, :)"""
3405 def rotate(self
, other
, context
=None):
3406 """Returns a rotated copy of self, value-of-other times."""
3408 context
= getcontext()
3410 ans
= self
._check
_nans
(other
, context
)
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
3425 topad
= context
.prec
- len(rotdig
)
3427 rotdig
= '0'*topad
+ rotdig
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."""
3437 context
= getcontext()
3439 ans
= self
._check
_nans
(other
, context
)
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
))
3457 def shift(self
, other
, context
=None):
3458 """Returns a shifted copy of self, value-of-other times."""
3460 context
= getcontext()
3462 ans
= self
._check
_nans
(other
, context
)
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
3477 return Decimal(self
)
3479 topad
= context
.prec
- len(rotdig
)
3481 rotdig
= '0'*topad
+ rotdig
3485 rotated
= rotdig
[:torot
]
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
),))
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).
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
3567 elif spec
['type'] in 'gG':
3568 if self
._exp
<= 0 and leftdigits
> -6:
3569 dotplace
= leftdigits
3573 # figure out main part of numeric string...
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
))
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'] == '%':
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
3601 This function is for *internal use only*.
3604 self
= object.__new
__(Decimal
)
3606 self
._int
= coefficient
3607 self
._exp
= exponent
3608 self
._is
_special
= special
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.
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
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):
3673 if _ignored_flags
is None:
3675 if not isinstance(flags
, dict):
3676 flags
= dict([(s
, int(s
in flags
)) for s
in _signals
])
3678 if traps
is not None and not isinstance(traps
, dict):
3679 traps
= dict([(s
, int(s
in traps
)) for s
in _signals
])
3681 for name
, val
in locals().items():
3683 setattr(self
, name
, _copy
.copy(getattr(DefaultContext
, name
)))
3685 setattr(self
, name
, val
)
3689 """Show the current context."""
3691 s
.append('Context(prec=%(prec)d, rounding=%(rounding)s, '
3692 'Emin=%(Emin)d, Emax=%(Emax)d, capitals=%(capitals)d'
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
)
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
)
3720 def _raise_error(self
, condition
, explanation
= None, *args
):
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
3750 self
._ignored
_flags
= (self
._ignored
_flags
+ 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)):
3758 self
._ignored
_flags
.remove(flag
)
3760 # We inherit object.__hash__, so we must deny this explicitly
3764 """Returns Etiny (= Emin - prec + 1)"""
3765 return int(self
.Emin
- self
.prec
+ 1)
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
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 "
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")
3807 def create_decimal_from_float(self
, f
):
3808 """Creates a new Decimal instance from a float but rounding using self
3811 >>> context = Context(prec=5, rounding=ROUND_DOWN)
3812 >>> context.create_decimal_from_float(3.1415926535897932)
3814 >>> context = Context(prec=5, traps=[Inexact])
3815 >>> context.create_decimal_from_float(3.1415926535897932)
3816 Traceback (most recent call last):
3821 d
= Decimal
.from_float(f
) # An exact conversion
3822 return d
._fix
(self
) # Apply the context rounding
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'))
3834 >>> ExtendedContext.abs(Decimal('-100'))
3836 >>> ExtendedContext.abs(Decimal('101.5'))
3838 >>> ExtendedContext.abs(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'))
3848 >>> ExtendedContext.add(Decimal('1E+2'), Decimal('1.01E+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'))
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
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'))
3883 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.1'))
3885 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('2.10'))
3887 >>> ExtendedContext.compare(Decimal('3'), Decimal('2.1'))
3889 >>> ExtendedContext.compare(Decimal('2.1'), Decimal('-3'))
3891 >>> ExtendedContext.compare(Decimal('-3'), Decimal('2.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'))
3905 >>> c.compare_signal(Decimal('2.1'), Decimal('2.1'))
3907 >>> c.flags[InvalidOperation] = 0
3908 >>> print c.flags[InvalidOperation]
3910 >>> c.compare_signal(Decimal('NaN'), Decimal('2.1'))
3912 >>> print c.flags[InvalidOperation]
3914 >>> c.flags[InvalidOperation] = 0
3915 >>> print c.flags[InvalidOperation]
3917 >>> c.compare_signal(Decimal('sNaN'), Decimal('2.1'))
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
3931 >>> ExtendedContext.compare_total(Decimal('12.73'), Decimal('127.9'))
3933 >>> ExtendedContext.compare_total(Decimal('-127'), Decimal('12'))
3935 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.3'))
3937 >>> ExtendedContext.compare_total(Decimal('12.30'), Decimal('12.30'))
3939 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('12.300'))
3941 >>> ExtendedContext.compare_total(Decimal('12.3'), Decimal('NaN'))
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'))
3958 >>> ExtendedContext.copy_abs(Decimal('-100'))
3963 def copy_decimal(self
, a
):
3964 """Returns a copy of the decimal objet.
3966 >>> ExtendedContext.copy_decimal(Decimal('2.1'))
3968 >>> ExtendedContext.copy_decimal(Decimal('-1.00'))
3973 def copy_negate(self
, a
):
3974 """Returns a copy of the operand with the sign inverted.
3976 >>> ExtendedContext.copy_negate(Decimal('101.5'))
3978 >>> ExtendedContext.copy_negate(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'))
3991 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('7.33'))
3993 >>> ExtendedContext.copy_sign(Decimal( '1.50'), Decimal('-7.33'))
3995 >>> ExtendedContext.copy_sign(Decimal('-1.50'), Decimal('-7.33'))
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'))
4009 >>> ExtendedContext.divide(Decimal('1'), Decimal('10'))
4011 >>> ExtendedContext.divide(Decimal('12'), Decimal('12'))
4013 >>> ExtendedContext.divide(Decimal('8.00'), Decimal('2'))
4015 >>> ExtendedContext.divide(Decimal('2.400'), Decimal('2.0'))
4017 >>> ExtendedContext.divide(Decimal('1000'), Decimal('100'))
4019 >>> ExtendedContext.divide(Decimal('1000'), Decimal('1'))
4021 >>> ExtendedContext.divide(Decimal('2.40E+6'), Decimal('2'))
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'))
4031 >>> ExtendedContext.divide_int(Decimal('10'), Decimal('3'))
4033 >>> ExtendedContext.divide_int(Decimal('1'), Decimal('0.3'))
4036 return a
.__floordiv
__(b
, context
=self
)
4038 def divmod(self
, a
, b
):
4039 return a
.__divmod
__(b
, context
=self
)
4044 >>> c = ExtendedContext.copy()
4047 >>> c.exp(Decimal('-Infinity'))
4049 >>> c.exp(Decimal('-1'))
4050 Decimal('0.367879441')
4051 >>> c.exp(Decimal('0'))
4053 >>> c.exp(Decimal('1'))
4054 Decimal('2.71828183')
4055 >>> c.exp(Decimal('0.693147181'))
4056 Decimal('2.00000000')
4057 >>> c.exp(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'))
4071 >>> ExtendedContext.fma(Decimal('3'), Decimal('-5'), Decimal('7'))
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'))
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
4095 >>> ExtendedContext.is_finite(Decimal('2.50'))
4097 >>> ExtendedContext.is_finite(Decimal('-0.3'))
4099 >>> ExtendedContext.is_finite(Decimal('0'))
4101 >>> ExtendedContext.is_finite(Decimal('Inf'))
4103 >>> ExtendedContext.is_finite(Decimal('NaN'))
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'))
4113 >>> ExtendedContext.is_infinite(Decimal('-Inf'))
4115 >>> ExtendedContext.is_infinite(Decimal('NaN'))
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'))
4126 >>> ExtendedContext.is_nan(Decimal('NaN'))
4128 >>> ExtendedContext.is_nan(Decimal('-sNaN'))
4133 def is_normal(self
, a
):
4134 """Return True if the operand is a normal number;
4135 otherwise return False.
4137 >>> c = ExtendedContext.copy()
4140 >>> c.is_normal(Decimal('2.50'))
4142 >>> c.is_normal(Decimal('0.1E-999'))
4144 >>> c.is_normal(Decimal('0.00'))
4146 >>> c.is_normal(Decimal('-Inf'))
4148 >>> c.is_normal(Decimal('NaN'))
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'))
4158 >>> ExtendedContext.is_qnan(Decimal('NaN'))
4160 >>> ExtendedContext.is_qnan(Decimal('sNaN'))
4165 def is_signed(self
, a
):
4166 """Return True if the operand is negative; otherwise return False.
4168 >>> ExtendedContext.is_signed(Decimal('2.50'))
4170 >>> ExtendedContext.is_signed(Decimal('-12'))
4172 >>> ExtendedContext.is_signed(Decimal('-0'))
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'))
4183 >>> ExtendedContext.is_snan(Decimal('NaN'))
4185 >>> ExtendedContext.is_snan(Decimal('sNaN'))
4190 def is_subnormal(self
, a
):
4191 """Return True if the operand is subnormal; otherwise return False.
4193 >>> c = ExtendedContext.copy()
4196 >>> c.is_subnormal(Decimal('2.50'))
4198 >>> c.is_subnormal(Decimal('0.1E-999'))
4200 >>> c.is_subnormal(Decimal('0.00'))
4202 >>> c.is_subnormal(Decimal('-Inf'))
4204 >>> c.is_subnormal(Decimal('NaN'))
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'))
4214 >>> ExtendedContext.is_zero(Decimal('2.50'))
4216 >>> ExtendedContext.is_zero(Decimal('-0E+2'))
4222 """Returns the natural (base e) logarithm of the operand.
4224 >>> c = ExtendedContext.copy()
4227 >>> c.ln(Decimal('0'))
4228 Decimal('-Infinity')
4229 >>> c.ln(Decimal('1.000'))
4231 >>> c.ln(Decimal('2.71828183'))
4232 Decimal('1.00000000')
4233 >>> c.ln(Decimal('10'))
4234 Decimal('2.30258509')
4235 >>> c.ln(Decimal('+Infinity'))
4238 return a
.ln(context
=self
)
4241 """Returns the base 10 logarithm of the operand.
4243 >>> c = ExtendedContext.copy()
4246 >>> c.log10(Decimal('0'))
4247 Decimal('-Infinity')
4248 >>> c.log10(Decimal('0.001'))
4250 >>> c.log10(Decimal('1.000'))
4252 >>> c.log10(Decimal('2'))
4253 Decimal('0.301029996')
4254 >>> c.log10(Decimal('10'))
4256 >>> c.log10(Decimal('70'))
4257 Decimal('1.84509804')
4258 >>> c.log10(Decimal('+Infinity'))
4261 return a
.log10(context
=self
)
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'))
4273 >>> ExtendedContext.logb(Decimal('2.50'))
4275 >>> ExtendedContext.logb(Decimal('0.03'))
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'))
4289 >>> ExtendedContext.logical_and(Decimal('0'), Decimal('1'))
4291 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('0'))
4293 >>> ExtendedContext.logical_and(Decimal('1'), Decimal('1'))
4295 >>> ExtendedContext.logical_and(Decimal('1100'), Decimal('1010'))
4297 >>> ExtendedContext.logical_and(Decimal('1111'), 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'))
4313 >>> ExtendedContext.logical_invert(Decimal('101010101'))
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'))
4325 >>> ExtendedContext.logical_or(Decimal('0'), Decimal('1'))
4327 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('0'))
4329 >>> ExtendedContext.logical_or(Decimal('1'), Decimal('1'))
4331 >>> ExtendedContext.logical_or(Decimal('1100'), Decimal('1010'))
4333 >>> ExtendedContext.logical_or(Decimal('1110'), Decimal('10'))
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'))
4345 >>> ExtendedContext.logical_xor(Decimal('0'), Decimal('1'))
4347 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('0'))
4349 >>> ExtendedContext.logical_xor(Decimal('1'), Decimal('1'))
4351 >>> ExtendedContext.logical_xor(Decimal('1100'), Decimal('1010'))
4353 >>> ExtendedContext.logical_xor(Decimal('1111'), Decimal('10'))
4356 return a
.logical_xor(b
, context
=self
)
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'))
4369 >>> ExtendedContext.max(Decimal('-10'), Decimal('3'))
4371 >>> ExtendedContext.max(Decimal('1.0'), Decimal('1'))
4373 >>> ExtendedContext.max(Decimal('7'), Decimal('NaN'))
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
)
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'))
4393 >>> ExtendedContext.min(Decimal('-10'), Decimal('3'))
4395 >>> ExtendedContext.min(Decimal('1.0'), Decimal('1'))
4397 >>> ExtendedContext.min(Decimal('7'), Decimal('NaN'))
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
)
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'))
4415 >>> ExtendedContext.minus(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'))
4430 >>> ExtendedContext.multiply(Decimal('7'), Decimal('3'))
4432 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('0.8'))
4434 >>> ExtendedContext.multiply(Decimal('0.9'), Decimal('-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()
4447 >>> ExtendedContext.next_minus(Decimal('1'))
4448 Decimal('0.999999999')
4449 >>> c.next_minus(Decimal('1E-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()
4464 >>> ExtendedContext.next_plus(Decimal('1'))
4465 Decimal('1.00000001')
4466 >>> c.next_plus(Decimal('-1E-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
4483 >>> c = ExtendedContext.copy()
4486 >>> c.next_toward(Decimal('1'), Decimal('2'))
4487 Decimal('1.00000001')
4488 >>> c.next_toward(Decimal('-1E-1007'), Decimal('1'))
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'))
4496 >>> c.next_toward(Decimal('-1.00000003'), Decimal('-10'))
4497 Decimal('-1.00000004')
4498 >>> c.next_toward(Decimal('0.00'), Decimal('-0.0000'))
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
4509 >>> ExtendedContext.normalize(Decimal('2.1'))
4511 >>> ExtendedContext.normalize(Decimal('-2.0'))
4513 >>> ExtendedContext.normalize(Decimal('1.200'))
4515 >>> ExtendedContext.normalize(Decimal('-120'))
4517 >>> ExtendedContext.normalize(Decimal('120.00'))
4519 >>> ExtendedContext.normalize(Decimal('0.00'))
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:
4539 >>> c = Context(ExtendedContext)
4542 >>> c.number_class(Decimal('Infinity'))
4544 >>> c.number_class(Decimal('1E-10'))
4546 >>> c.number_class(Decimal('2.50'))
4548 >>> c.number_class(Decimal('0.1E-999'))
4550 >>> c.number_class(Decimal('0'))
4552 >>> c.number_class(Decimal('-0'))
4554 >>> c.number_class(Decimal('-0.1E-999'))
4556 >>> c.number_class(Decimal('-1E-10'))
4558 >>> c.number_class(Decimal('-2.50'))
4560 >>> c.number_class(Decimal('-Infinity'))
4562 >>> c.number_class(Decimal('NaN'))
4564 >>> c.number_class(Decimal('-NaN'))
4566 >>> c.number_class(Decimal('sNaN'))
4569 return a
.number_class(context
=self
)
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'))
4580 >>> ExtendedContext.plus(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
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
4607 >>> c = ExtendedContext.copy()
4610 >>> c.power(Decimal('2'), Decimal('3'))
4612 >>> c.power(Decimal('-2'), Decimal('3'))
4614 >>> c.power(Decimal('2'), Decimal('-3'))
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'))
4622 >>> c.power(Decimal('Infinity'), Decimal('0'))
4624 >>> c.power(Decimal('Infinity'), Decimal('1'))
4626 >>> c.power(Decimal('-Infinity'), Decimal('-1'))
4628 >>> c.power(Decimal('-Infinity'), Decimal('0'))
4630 >>> c.power(Decimal('-Infinity'), Decimal('1'))
4631 Decimal('-Infinity')
4632 >>> c.power(Decimal('-Infinity'), Decimal('2'))
4634 >>> c.power(Decimal('0'), Decimal('0'))
4637 >>> c.power(Decimal('3'), Decimal('7'), Decimal('16'))
4639 >>> c.power(Decimal('-3'), Decimal('7'), Decimal('16'))
4641 >>> c.power(Decimal('-3'), Decimal('8'), Decimal('16'))
4643 >>> c.power(Decimal('3'), Decimal('7'), Decimal('-16'))
4645 >>> c.power(Decimal('23E12345'), Decimal('67E189'), Decimal('123456789'))
4647 >>> c.power(Decimal('-0'), Decimal('17'), Decimal('1729'))
4649 >>> c.power(Decimal('-23'), Decimal('0'), Decimal('65537'))
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'))
4674 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.01'))
4676 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('0.1'))
4678 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+0'))
4680 >>> ExtendedContext.quantize(Decimal('2.17'), Decimal('1e+1'))
4682 >>> ExtendedContext.quantize(Decimal('-Inf'), Decimal('Infinity'))
4683 Decimal('-Infinity')
4684 >>> ExtendedContext.quantize(Decimal('2'), Decimal('Infinity'))
4686 >>> ExtendedContext.quantize(Decimal('-0.1'), Decimal('1'))
4688 >>> ExtendedContext.quantize(Decimal('-0'), Decimal('1e+5'))
4690 >>> ExtendedContext.quantize(Decimal('+35236450.6'), Decimal('1e-2'))
4692 >>> ExtendedContext.quantize(Decimal('-35236450.6'), Decimal('1e-2'))
4694 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-1'))
4696 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e-0'))
4698 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+1'))
4700 >>> ExtendedContext.quantize(Decimal('217'), Decimal('1e+2'))
4703 return a
.quantize(b
, context
=self
)
4706 """Just returns 10, as this is Decimal, :)
4708 >>> ExtendedContext.radix()
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'))
4727 >>> ExtendedContext.remainder(Decimal('10'), Decimal('3'))
4729 >>> ExtendedContext.remainder(Decimal('-10'), Decimal('3'))
4731 >>> ExtendedContext.remainder(Decimal('10.2'), Decimal('1'))
4733 >>> ExtendedContext.remainder(Decimal('10'), Decimal('0.3'))
4735 >>> ExtendedContext.remainder(Decimal('3.6'), Decimal('1.3'))
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
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'))
4752 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('6'))
4754 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('3'))
4756 >>> ExtendedContext.remainder_near(Decimal('-10'), Decimal('3'))
4758 >>> ExtendedContext.remainder_near(Decimal('10.2'), Decimal('1'))
4760 >>> ExtendedContext.remainder_near(Decimal('10'), Decimal('0.3'))
4762 >>> ExtendedContext.remainder_near(Decimal('3.6'), Decimal('1.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'))
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
4795 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.001'))
4797 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('0.01'))
4799 >>> ExtendedContext.same_quantum(Decimal('2.17'), Decimal('1'))
4801 >>> ExtendedContext.same_quantum(Decimal('Inf'), Decimal('-Inf'))
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'))
4811 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('0'))
4813 >>> ExtendedContext.scaleb(Decimal('7.50'), Decimal('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'))
4832 >>> ExtendedContext.shift(Decimal('123456789'), Decimal('-2'))
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
)
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
4847 >>> ExtendedContext.sqrt(Decimal('0'))
4849 >>> ExtendedContext.sqrt(Decimal('-0'))
4851 >>> ExtendedContext.sqrt(Decimal('0.39'))
4852 Decimal('0.624499800')
4853 >>> ExtendedContext.sqrt(Decimal('100'))
4855 >>> ExtendedContext.sqrt(Decimal('1'))
4857 >>> ExtendedContext.sqrt(Decimal('1.0'))
4859 >>> ExtendedContext.sqrt(Decimal('1.00'))
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'))
4875 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('1.30'))
4877 >>> ExtendedContext.subtract(Decimal('1.3'), Decimal('2.07'))
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
4906 >>> ExtendedContext.to_integral_exact(Decimal('2.1'))
4908 >>> ExtendedContext.to_integral_exact(Decimal('100'))
4910 >>> ExtendedContext.to_integral_exact(Decimal('100.0'))
4912 >>> ExtendedContext.to_integral_exact(Decimal('101.5'))
4914 >>> ExtendedContext.to_integral_exact(Decimal('-101.5'))
4916 >>> ExtendedContext.to_integral_exact(Decimal('10E+5'))
4918 >>> ExtendedContext.to_integral_exact(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'))
4936 >>> ExtendedContext.to_integral_value(Decimal('100'))
4938 >>> ExtendedContext.to_integral_value(Decimal('100.0'))
4940 >>> ExtendedContext.to_integral_value(Decimal('101.5'))
4942 >>> ExtendedContext.to_integral_value(Decimal('-101.5'))
4944 >>> ExtendedContext.to_integral_value(Decimal('10E+5'))
4946 >>> ExtendedContext.to_integral_value(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')
4960 # exp: None, int, or string
4962 def __init__(self
, value
=None):
4967 elif isinstance(value
, Decimal
):
4968 self
.sign
= value
._sign
4969 self
.int = int(value
._int
)
4970 self
.exp
= value
._exp
4972 # assert isinstance(value, tuple)
4973 self
.sign
= value
[0]
4978 return "(%r, %r, %r)" % (self
.sign
, self
.int, self
.exp
)
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
:
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
:
5008 tmp
.int *= 10 ** (tmp
.exp
- other
.exp
)
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,
5028 raise ValueError("The argument to _nbits should be nonnegative.")
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.")
5044 b
, a
= a
, a
--n
//a
>>1
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.
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
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
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
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.
5094 # argument reduction; R = number of reductions performed
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
))
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
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
5125 f
= e
+l
- (e
+l
>= 1)
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
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)
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.
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).
5158 f
= e
+l
- (e
+l
>= 1)
5160 # compute approximation to 10**p*log(d), with error < 27
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
5171 # p <= 0: just approximate the whole thing by 0; error < 2.31
5174 # compute approximation to f*10**p*log(10), with error < 11.
5176 extra
= len(str(abs(f
)))-1
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
)
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__."""
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).
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
5213 # compute p+extra digits, correct to within 1ulp
5215 digits
= str(_div_nearest(_ilog(10*M
, M
), 100))
5216 if digits
[-extra
:] != '0'*extra
:
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
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
)
5253 for i
in xrange(T
-1, 0, -1):
5254 y
= _div_nearest(x
*(Mshift
+ y
), Mshift
* i
)
5257 for k
in xrange(R
-1, -1, -1):
5258 Mshift
= long(M
)<<(k
+2)
5259 y
= _div_nearest(y
*(y
+Mshift
), Mshift
)
5264 """Compute an approximation to exp(c*10**e), with p decimal places of
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
5280 # compute log(10) with extra precision = adjusted exponent of c*10**e
5281 extra
= max(0, e
+ len(str(c
)) - 1)
5284 # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
5288 cshift
= c
*10**shift
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)
5323 pc
= lxc
*yc
*10**shift
5325 pc
= _div_nearest(lxc
*yc
, 10**-shift
)
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
5333 coeff
, exp
= 10**p
-1, -p
5335 coeff
, exp
= _dexp(pc
, -(p
+1), p
+1)
5336 coeff
= _div_nearest(coeff
, 10)
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."""
5346 raise ValueError("The argument to _log10_lb should be nonnegative.")
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
):
5359 if isinstance(other
, (int, long)):
5360 return Decimal(other
)
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
],
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
5384 BasicContext
= Context(
5385 prec
=9, rounding
=ROUND_HALF_UP
,
5386 traps
=[DivisionByZero
, Overflow
, InvalidOperation
, Clamped
, Underflow
],
5390 ExtendedContext
= Context(
5391 prec
=9, rounding
=ROUND_HALF_EVEN
,
5397 ##### crud for parsing strings #############################################
5399 # Regular expression used for parsing numeric strings. Additional
5402 # 1. Uncomment the two '\s*' lines to allow leading and/or trailing
5403 # whitespace. But note that the specification disallows whitespace in
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].
5415 _parser
= re
.compile(r
""" # A numeric string consists of:
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)
5428 (?P<diag>[0-9]*) # with (possibly empty) diagnostic info.
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
5454 (?P<minimumwidth>(?!0)\d+)?
5455 (?:\.(?P<precision>0|(?!0)\d+))?
5456 (?P<type>[eEfFgG%])?
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
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
)
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
)
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)
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 '-+':
5540 if spec_dict
['sign'] in ' +':
5541 sign
= spec_dict
['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']
5552 result
= padding
+ sign
+ body
5554 result
= sign
+ body
+ padding
5556 result
= sign
+ padding
+ body
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
)
5567 ##### Useful Constants (internal use only) ################################
5570 _Infinity
= Decimal('Inf')
5571 _NegativeInfinity
= Decimal('-Inf')
5572 _NaN
= Decimal('NaN')
5575 _NegativeOne
= Decimal(-1)
5577 # _SignedInfinity[sign] is infinity w/ that sign
5578 _SignedInfinity
= (_Infinity
, _NegativeInfinity
)
5582 if __name__
== '__main__':
5584 doctest
.testmod(sys
.modules
[__name__
])