Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes | Properties | Private Member Functions | Private Attributes | Static Private Attributes
decimal.Decimal Class Reference

Decimal class #######################################################. More...

Inheritance diagram for decimal.Decimal:
Inheritance graph
[legend]
Collaboration diagram for decimal.Decimal:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __new__
def from_float
def __bool__
def __eq__
def __ne__
def __lt__
def __le__
def __gt__
def __ge__
def compare
def __hash__
def as_tuple
def __repr__
def __str__
def to_eng_string
def __neg__
def __pos__
def __abs__
def __add__
def __sub__
def __rsub__
def __mul__
def __truediv__
def __rtruediv__
def __divmod__
def __rdivmod__
def __mod__
def __rmod__
def remainder_near
def __floordiv__
def __rfloordiv__
def __float__
def __int__
def real
def imag
def conjugate
def __complex__
def __round__
def __floor__
def __ceil__
def fma
def __pow__
def __rpow__
def normalize
def quantize
def same_quantum
def to_integral_exact
def to_integral_value
def sqrt
def max
def min
def adjusted
def canonical
def compare_signal
def compare_total
def compare_total_mag
def copy_abs
def copy_negate
def copy_sign
def exp
def is_canonical
def is_finite
def is_infinite
def is_nan
def is_normal
def is_qnan
def is_signed
def is_snan
def is_subnormal
def is_zero
def ln
def log10
def logb
def logical_and
def logical_invert
def logical_or
def logical_xor
def max_mag
def min_mag
def next_minus
def next_plus
def next_toward
def number_class
def radix
def rotate
def scaleb
def shift
def __reduce__
def __copy__
def __deepcopy__
def __format__

Public Attributes

_PyObject_HEAD_EXTRA Py_ssize_t ob_refcnt
struct _typeobjectob_type

Static Public Attributes

tuple from_float = classmethod(from_float)
 to_integral = to_integral_value

Properties

 real = property(real)
 imag = property(imag)

Private Member Functions

def _isnan
def _isinfinity
def _check_nans
def _compare_check_nans
def _cmp
def _divide
def _fix_nan
def _fix
def _round_down
def _round_up
def _round_half_up
def _round_half_down
def _round_half_even
def _round_ceiling
def _round_floor
def _round_05up
def _power_modulo
def _power_exact
def _rescale
def _round
def _isinteger
def _iseven
def _ln_exp_bound
def _log10_exp_bound
def _islogical
def _fill_logical

Private Attributes

 _sign
 _int
 _exp
 _is_special

Static Private Attributes

tuple __slots__ = ('_exp','_int','_sign', '_is_special')
 __radd__ = __add__
 __rmul__ = __mul__
 __trunc__ = __int__
tuple _pick_rounding_function

Detailed Description

Decimal class #######################################################.

Floating point class for decimal arithmetic.

Definition at line 508 of file decimal.py.


Member Function Documentation

def decimal.Decimal.__abs__ (   self,
  round = True,
  context = None 
)
Returns the absolute value of self.

If the keyword argument 'round' is false, do not round.  The
expression self.__abs__(round=False) is equivalent to
self.copy_abs().

Definition at line 1081 of file decimal.py.

01081 
01082     def __abs__(self, round=True, context=None):
01083         """Returns the absolute value of self.
01084 
01085         If the keyword argument 'round' is false, do not round.  The
01086         expression self.__abs__(round=False) is equivalent to
01087         self.copy_abs().
01088         """
01089         if not round:
01090             return self.copy_abs()
01091 
01092         if self._is_special:
01093             ans = self._check_nans(context=context)
01094             if ans:
01095                 return ans
01096 
01097         if self._sign:
01098             ans = self.__neg__(context=context)
01099         else:
01100             ans = self.__pos__(context=context)
01101 
01102         return ans

Here is the call graph for this function:

def decimal.Decimal.__add__ (   self,
  other,
  context = None 
)
Returns self + other.

-INF + INF (or the reverse) cause InvalidOperation errors.

Definition at line 1103 of file decimal.py.

01103 
01104     def __add__(self, other, context=None):
01105         """Returns self + other.
01106 
01107         -INF + INF (or the reverse) cause InvalidOperation errors.
01108         """
01109         other = _convert_other(other)
01110         if other is NotImplemented:
01111             return other
01112 
01113         if context is None:
01114             context = getcontext()
01115 
01116         if self._is_special or other._is_special:
01117             ans = self._check_nans(other, context)
01118             if ans:
01119                 return ans
01120 
01121             if self._isinfinity():
01122                 # If both INF, same sign => same as both, opposite => error.
01123                 if self._sign != other._sign and other._isinfinity():
01124                     return context._raise_error(InvalidOperation, '-INF + INF')
01125                 return Decimal(self)
01126             if other._isinfinity():
01127                 return Decimal(other)  # Can't both be infinity here
01128 
01129         exp = min(self._exp, other._exp)
01130         negativezero = 0
01131         if context.rounding == ROUND_FLOOR and self._sign != other._sign:
01132             # If the answer is 0, the sign should be negative, in this case.
01133             negativezero = 1
01134 
01135         if not self and not other:
01136             sign = min(self._sign, other._sign)
01137             if negativezero:
01138                 sign = 1
01139             ans = _dec_from_triple(sign, '0', exp)
01140             ans = ans._fix(context)
01141             return ans
01142         if not self:
01143             exp = max(exp, other._exp - context.prec-1)
01144             ans = other._rescale(exp, context.rounding)
01145             ans = ans._fix(context)
01146             return ans
01147         if not other:
01148             exp = max(exp, self._exp - context.prec-1)
01149             ans = self._rescale(exp, context.rounding)
01150             ans = ans._fix(context)
01151             return ans
01152 
01153         op1 = _WorkRep(self)
01154         op2 = _WorkRep(other)
01155         op1, op2 = _normalize(op1, op2, context.prec)
01156 
01157         result = _WorkRep()
01158         if op1.sign != op2.sign:
01159             # Equal and opposite
01160             if op1.int == op2.int:
01161                 ans = _dec_from_triple(negativezero, '0', exp)
01162                 ans = ans._fix(context)
01163                 return ans
01164             if op1.int < op2.int:
01165                 op1, op2 = op2, op1
01166                 # OK, now abs(op1) > abs(op2)
01167             if op1.sign == 1:
01168                 result.sign = 1
01169                 op1.sign, op2.sign = op2.sign, op1.sign
01170             else:
01171                 result.sign = 0
01172                 # So we know the sign, and op1 > 0.
01173         elif op1.sign == 1:
01174             result.sign = 1
01175             op1.sign, op2.sign = (0, 0)
01176         else:
01177             result.sign = 0
01178         # Now, op1 > abs(op2) > 0
01179 
01180         if op2.sign == 0:
01181             result.int = op1.int + op2.int
01182         else:
01183             result.int = op1.int - op2.int
01184 
01185         result.exp = op1.exp
01186         ans = Decimal(result)
01187         ans = ans._fix(context)
01188         return ans

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__bool__ (   self)
Return True if self is nonzero; otherwise return False.

NaNs and infinities are considered nonzero.

Definition at line 795 of file decimal.py.

00795 
00796     def __bool__(self):
00797         """Return True if self is nonzero; otherwise return False.
00798 
00799         NaNs and infinities are considered nonzero.
00800         """
00801         return self._is_special or self._int != '0'

def decimal.Decimal.__ceil__ (   self)
Return the ceiling of self, as an integer.

For a finite Decimal instance self, return the least integer n
such that n >= self.  If self is infinite or a NaN then a
Python exception is raised.

Definition at line 1847 of file decimal.py.

01847 
01848     def __ceil__(self):
01849         """Return the ceiling of self, as an integer.
01850 
01851         For a finite Decimal instance self, return the least integer n
01852         such that n >= self.  If self is infinite or a NaN then a
01853         Python exception is raised.
01854 
01855         """
01856         if self._is_special:
01857             if self.is_nan():
01858                 raise ValueError("cannot round a NaN")
01859             else:
01860                 raise OverflowError("cannot round an infinity")
01861         return int(self._rescale(0, ROUND_CEILING))

Here is the call graph for this function:

Definition at line 1586 of file decimal.py.

01586 
01587     def __complex__(self):
01588         return complex(float(self))

def decimal.Decimal.__copy__ (   self)

Definition at line 3663 of file decimal.py.

03663 
03664     def __copy__(self):
03665         if type(self) is Decimal:
03666             return self     # I'm immutable; therefore I am my own clone
03667         return self.__class__(str(self))

def decimal.Decimal.__deepcopy__ (   self,
  memo 
)

Definition at line 3668 of file decimal.py.

03668 
03669     def __deepcopy__(self, memo):
03670         if type(self) is Decimal:
03671             return self     # My components are also immutable
03672         return self.__class__(str(self))

def decimal.Decimal.__divmod__ (   self,
  other,
  context = None 
)
Return (self // other, self % other)

Definition at line 1369 of file decimal.py.

01369 
01370     def __divmod__(self, other, context=None):
01371         """
01372         Return (self // other, self % other)
01373         """
01374         other = _convert_other(other)
01375         if other is NotImplemented:
01376             return other
01377 
01378         if context is None:
01379             context = getcontext()
01380 
01381         ans = self._check_nans(other, context)
01382         if ans:
01383             return (ans, ans)
01384 
01385         sign = self._sign ^ other._sign
01386         if self._isinfinity():
01387             if other._isinfinity():
01388                 ans = context._raise_error(InvalidOperation, 'divmod(INF, INF)')
01389                 return ans, ans
01390             else:
01391                 return (_SignedInfinity[sign],
01392                         context._raise_error(InvalidOperation, 'INF % x'))
01393 
01394         if not other:
01395             if not self:
01396                 ans = context._raise_error(DivisionUndefined, 'divmod(0, 0)')
01397                 return ans, ans
01398             else:
01399                 return (context._raise_error(DivisionByZero, 'x // 0', sign),
01400                         context._raise_error(InvalidOperation, 'x % 0'))
01401 
01402         quotient, remainder = self._divide(other, context)
01403         remainder = remainder._fix(context)
01404         return quotient, remainder

Here is the call graph for this function:

def decimal.Decimal.__eq__ (   self,
  other,
  context = None 
)

Definition at line 866 of file decimal.py.

00866 
00867     def __eq__(self, other, context=None):
00868         self, other = _convert_for_comparison(self, other, equality_op=True)
00869         if other is NotImplemented:
00870             return other
00871         if self._check_nans(other, context):
00872             return False
00873         return self._cmp(other) == 0

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__float__ (   self)
Float representation.

Definition at line 1556 of file decimal.py.

01556 
01557     def __float__(self):
01558         """Float representation."""
01559         return float(str(self))

def decimal.Decimal.__floor__ (   self)
Return the floor of self, as an integer.

For a finite Decimal instance self, return the greatest
integer n such that n <= self.  If self is infinite or a NaN
then a Python exception is raised.

Definition at line 1832 of file decimal.py.

01832 
01833     def __floor__(self):
01834         """Return the floor of self, as an integer.
01835 
01836         For a finite Decimal instance self, return the greatest
01837         integer n such that n <= self.  If self is infinite or a NaN
01838         then a Python exception is raised.
01839 
01840         """
01841         if self._is_special:
01842             if self.is_nan():
01843                 raise ValueError("cannot round a NaN")
01844             else:
01845                 raise OverflowError("cannot round an infinity")
01846         return int(self._rescale(0, ROUND_FLOOR))

Here is the call graph for this function:

def decimal.Decimal.__floordiv__ (   self,
  other,
  context = None 
)
self // other

Definition at line 1521 of file decimal.py.

01521 
01522     def __floordiv__(self, other, context=None):
01523         """self // other"""
01524         other = _convert_other(other)
01525         if other is NotImplemented:
01526             return other
01527 
01528         if context is None:
01529             context = getcontext()
01530 
01531         ans = self._check_nans(other, context)
01532         if ans:
01533             return ans
01534 
01535         if self._isinfinity():
01536             if other._isinfinity():
01537                 return context._raise_error(InvalidOperation, 'INF // INF')
01538             else:
01539                 return _SignedInfinity[self._sign ^ other._sign]
01540 
01541         if not other:
01542             if self:
01543                 return context._raise_error(DivisionByZero, 'x // 0',
01544                                             self._sign ^ other._sign)
01545             else:
01546                 return context._raise_error(DivisionUndefined, '0 // 0')
01547 
01548         return self._divide(other, context)[0]

Here is the call graph for this function:

def decimal.Decimal.__format__ (   self,
  specifier,
  context = None,
  _localeconv = None 
)
Format a Decimal instance according to the given specifier.

The specifier should be a standard format specifier, with the
form described in PEP 3101.  Formatting types 'e', 'E', 'f',
'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
type is omitted it defaults to 'g' or 'G', depending on the
value of context.capitals.

Definition at line 3675 of file decimal.py.

03675 
03676     def __format__(self, specifier, context=None, _localeconv=None):
03677         """Format a Decimal instance according to the given specifier.
03678 
03679         The specifier should be a standard format specifier, with the
03680         form described in PEP 3101.  Formatting types 'e', 'E', 'f',
03681         'F', 'g', 'G', 'n' and '%' are supported.  If the formatting
03682         type is omitted it defaults to 'g' or 'G', depending on the
03683         value of context.capitals.
03684         """
03685 
03686         # Note: PEP 3101 says that if the type is not present then
03687         # there should be at least one digit after the decimal point.
03688         # We take the liberty of ignoring this requirement for
03689         # Decimal---it's presumably there to make sure that
03690         # format(float, '') behaves similarly to str(float).
03691         if context is None:
03692             context = getcontext()
03693 
03694         spec = _parse_format_specifier(specifier, _localeconv=_localeconv)
03695 
03696         # special values don't care about the type or precision
03697         if self._is_special:
03698             sign = _format_sign(self._sign, spec)
03699             body = str(self.copy_abs())
03700             return _format_align(sign, body, spec)
03701 
03702         # a type of None defaults to 'g' or 'G', depending on context
03703         if spec['type'] is None:
03704             spec['type'] = ['g', 'G'][context.capitals]
03705 
03706         # if type is '%', adjust exponent of self accordingly
03707         if spec['type'] == '%':
03708             self = _dec_from_triple(self._sign, self._int, self._exp+2)
03709 
03710         # round if necessary, taking rounding mode from the context
03711         rounding = context.rounding
03712         precision = spec['precision']
03713         if precision is not None:
03714             if spec['type'] in 'eE':
03715                 self = self._round(precision+1, rounding)
03716             elif spec['type'] in 'fF%':
03717                 self = self._rescale(-precision, rounding)
03718             elif spec['type'] in 'gG' and len(self._int) > precision:
03719                 self = self._round(precision, rounding)
03720         # special case: zeros with a positive exponent can't be
03721         # represented in fixed point; rescale them to 0e0.
03722         if not self and self._exp > 0 and spec['type'] in 'fF%':
03723             self = self._rescale(0, rounding)
03724 
03725         # figure out placement of the decimal point
03726         leftdigits = self._exp + len(self._int)
03727         if spec['type'] in 'eE':
03728             if not self and precision is not None:
03729                 dotplace = 1 - precision
03730             else:
03731                 dotplace = 1
03732         elif spec['type'] in 'fF%':
03733             dotplace = leftdigits
03734         elif spec['type'] in 'gG':
03735             if self._exp <= 0 and leftdigits > -6:
03736                 dotplace = leftdigits
03737             else:
03738                 dotplace = 1
03739 
03740         # find digits before and after decimal point, and get exponent
03741         if dotplace < 0:
03742             intpart = '0'
03743             fracpart = '0'*(-dotplace) + self._int
03744         elif dotplace > len(self._int):
03745             intpart = self._int + '0'*(dotplace-len(self._int))
03746             fracpart = ''
03747         else:
03748             intpart = self._int[:dotplace] or '0'
03749             fracpart = self._int[dotplace:]
03750         exp = leftdigits-dotplace
03751 
03752         # done with the decimal-specific stuff;  hand over the rest
03753         # of the formatting to the _format_number function
03754         return _format_number(self._sign, intpart, fracpart, exp, spec)

Here is the call graph for this function:

def decimal.Decimal.__ge__ (   self,
  other,
  context = None 
)

Definition at line 910 of file decimal.py.

00910 
00911     def __ge__(self, other, context=None):
00912         self, other = _convert_for_comparison(self, other)
00913         if other is NotImplemented:
00914             return other
00915         ans = self._compare_check_nans(other, context)
00916         if ans:
00917             return False
00918         return self._cmp(other) >= 0

Here is the call graph for this function:

def decimal.Decimal.__gt__ (   self,
  other,
  context = None 
)

Definition at line 901 of file decimal.py.

00901 
00902     def __gt__(self, other, context=None):
00903         self, other = _convert_for_comparison(self, other)
00904         if other is NotImplemented:
00905             return other
00906         ans = self._compare_check_nans(other, context)
00907         if ans:
00908             return False
00909         return self._cmp(other) > 0

Here is the call graph for this function:

def decimal.Decimal.__hash__ (   self)
x.__hash__() <==> hash(x)

Definition at line 938 of file decimal.py.

00938 
00939     def __hash__(self):
00940         """x.__hash__() <==> hash(x)"""
00941 
00942         # In order to make sure that the hash of a Decimal instance
00943         # agrees with the hash of a numerically equal integer, float
00944         # or Fraction, we follow the rules for numeric hashes outlined
00945         # in the documentation.  (See library docs, 'Built-in Types').
00946         if self._is_special:
00947             if self.is_snan():
00948                 raise TypeError('Cannot hash a signaling NaN value.')
00949             elif self.is_nan():
00950                 return _PyHASH_NAN
00951             else:
00952                 if self._sign:
00953                     return -_PyHASH_INF
00954                 else:
00955                     return _PyHASH_INF
00956 
00957         if self._exp >= 0:
00958             exp_hash = pow(10, self._exp, _PyHASH_MODULUS)
00959         else:
00960             exp_hash = pow(_PyHASH_10INV, -self._exp, _PyHASH_MODULUS)
00961         hash_ = int(self._int) * exp_hash % _PyHASH_MODULUS
00962         ans = hash_ if self >= 0 else -hash_
00963         return -2 if ans == -1 else ans

Here is the call graph for this function:

def decimal.Decimal.__int__ (   self)
Converts self to an int, truncating if necessary.

Definition at line 1560 of file decimal.py.

01560 
01561     def __int__(self):
01562         """Converts self to an int, truncating if necessary."""
01563         if self._is_special:
01564             if self._isnan():
01565                 raise ValueError("Cannot convert NaN to integer")
01566             elif self._isinfinity():
01567                 raise OverflowError("Cannot convert infinity to integer")
01568         s = (-1)**self._sign
01569         if self._exp >= 0:
01570             return s*int(self._int)*10**self._exp
01571         else:
01572             return s*int(self._int[:self._exp] or '0')

Here is the call graph for this function:

def decimal.Decimal.__le__ (   self,
  other,
  context = None 
)

Definition at line 892 of file decimal.py.

00892 
00893     def __le__(self, other, context=None):
00894         self, other = _convert_for_comparison(self, other)
00895         if other is NotImplemented:
00896             return other
00897         ans = self._compare_check_nans(other, context)
00898         if ans:
00899             return False
00900         return self._cmp(other) <= 0

Here is the call graph for this function:

def decimal.Decimal.__lt__ (   self,
  other,
  context = None 
)

Definition at line 883 of file decimal.py.

00883 
00884     def __lt__(self, other, context=None):
00885         self, other = _convert_for_comparison(self, other)
00886         if other is NotImplemented:
00887             return other
00888         ans = self._compare_check_nans(other, context)
00889         if ans:
00890             return False
00891         return self._cmp(other) < 0

Here is the call graph for this function:

def decimal.Decimal.__mod__ (   self,
  other,
  context = None 
)
self % other

Definition at line 1412 of file decimal.py.

01412 
01413     def __mod__(self, other, context=None):
01414         """
01415         self % other
01416         """
01417         other = _convert_other(other)
01418         if other is NotImplemented:
01419             return other
01420 
01421         if context is None:
01422             context = getcontext()
01423 
01424         ans = self._check_nans(other, context)
01425         if ans:
01426             return ans
01427 
01428         if self._isinfinity():
01429             return context._raise_error(InvalidOperation, 'INF % x')
01430         elif not other:
01431             if self:
01432                 return context._raise_error(InvalidOperation, 'x % 0')
01433             else:
01434                 return context._raise_error(DivisionUndefined, '0 % 0')
01435 
01436         remainder = self._divide(other, context)[1]
01437         remainder = remainder._fix(context)
01438         return remainder

Here is the call graph for this function:

def decimal.Decimal.__mul__ (   self,
  other,
  context = None 
)
Return self * other.

(+-) INF * 0 (or its reverse) raise InvalidOperation.

Definition at line 1213 of file decimal.py.

01213 
01214     def __mul__(self, other, context=None):
01215         """Return self * other.
01216 
01217         (+-) INF * 0 (or its reverse) raise InvalidOperation.
01218         """
01219         other = _convert_other(other)
01220         if other is NotImplemented:
01221             return other
01222 
01223         if context is None:
01224             context = getcontext()
01225 
01226         resultsign = self._sign ^ other._sign
01227 
01228         if self._is_special or other._is_special:
01229             ans = self._check_nans(other, context)
01230             if ans:
01231                 return ans
01232 
01233             if self._isinfinity():
01234                 if not other:
01235                     return context._raise_error(InvalidOperation, '(+-)INF * 0')
01236                 return _SignedInfinity[resultsign]
01237 
01238             if other._isinfinity():
01239                 if not self:
01240                     return context._raise_error(InvalidOperation, '0 * (+-)INF')
01241                 return _SignedInfinity[resultsign]
01242 
01243         resultexp = self._exp + other._exp
01244 
01245         # Special case for multiplying by zero
01246         if not self or not other:
01247             ans = _dec_from_triple(resultsign, '0', resultexp)
01248             # Fixing in case the exponent is out of bounds
01249             ans = ans._fix(context)
01250             return ans
01251 
01252         # Special case for multiplying by power of 10
01253         if self._int == '1':
01254             ans = _dec_from_triple(resultsign, other._int, resultexp)
01255             ans = ans._fix(context)
01256             return ans
01257         if other._int == '1':
01258             ans = _dec_from_triple(resultsign, self._int, resultexp)
01259             ans = ans._fix(context)
01260             return ans
01261 
01262         op1 = _WorkRep(self)
01263         op2 = _WorkRep(other)
01264 
01265         ans = _dec_from_triple(resultsign, str(op1.int * op2.int), resultexp)
01266         ans = ans._fix(context)
01267 
        return ans

Here is the call graph for this function:

def decimal.Decimal.__ne__ (   self,
  other,
  context = None 
)

Definition at line 874 of file decimal.py.

00874 
00875     def __ne__(self, other, context=None):
00876         self, other = _convert_for_comparison(self, other, equality_op=True)
00877         if other is NotImplemented:
00878             return other
00879         if self._check_nans(other, context):
00880             return True
00881         return self._cmp(other) != 0
00882 

Here is the call graph for this function:

def decimal.Decimal.__neg__ (   self,
  context = None 
)
Returns a copy with the sign switched.

Rounds, if it has reason.

Definition at line 1038 of file decimal.py.

01038 
01039     def __neg__(self, context=None):
01040         """Returns a copy with the sign switched.
01041 
01042         Rounds, if it has reason.
01043         """
01044         if self._is_special:
01045             ans = self._check_nans(context=context)
01046             if ans:
01047                 return ans
01048 
01049         if context is None:
01050             context = getcontext()
01051 
01052         if not self and context.rounding != ROUND_FLOOR:
01053             # -Decimal('0') is Decimal('0'), not Decimal('-0'), except
01054             # in ROUND_FLOOR rounding mode.
01055             ans = self.copy_abs()
01056         else:
01057             ans = self.copy_negate()
01058 
01059         return ans._fix(context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__new__ (   cls,
  value = "0",
  context = None 
)
Create a decimal point instance.

>>> Decimal('3.14')              # string input
Decimal('3.14')
>>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
Decimal('3.14')
>>> Decimal(314)                 # int
Decimal('314')
>>> Decimal(Decimal(314))        # another decimal instance
Decimal('314')
>>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
Decimal('3.14')

Definition at line 517 of file decimal.py.

00517 
00518     def __new__(cls, value="0", context=None):
00519         """Create a decimal point instance.
00520 
00521         >>> Decimal('3.14')              # string input
00522         Decimal('3.14')
00523         >>> Decimal((0, (3, 1, 4), -2))  # tuple (sign, digit_tuple, exponent)
00524         Decimal('3.14')
00525         >>> Decimal(314)                 # int
00526         Decimal('314')
00527         >>> Decimal(Decimal(314))        # another decimal instance
00528         Decimal('314')
00529         >>> Decimal('  3.14  \\n')        # leading and trailing whitespace okay
00530         Decimal('3.14')
00531         """
00532 
00533         # Note that the coefficient, self._int, is actually stored as
00534         # a string rather than as a tuple of digits.  This speeds up
00535         # the "digits to integer" and "integer to digits" conversions
00536         # that are used in almost every arithmetic operation on
00537         # Decimals.  This is an internal detail: the as_tuple function
00538         # and the Decimal constructor still deal with tuples of
00539         # digits.
00540 
00541         self = object.__new__(cls)
00542 
00543         # From a string
00544         # REs insist on real strings, so we can too.
00545         if isinstance(value, str):
00546             m = _parser(value.strip())
00547             if m is None:
00548                 if context is None:
00549                     context = getcontext()
00550                 return context._raise_error(ConversionSyntax,
00551                                 "Invalid literal for Decimal: %r" % value)
00552 
00553             if m.group('sign') == "-":
00554                 self._sign = 1
00555             else:
00556                 self._sign = 0
00557             intpart = m.group('int')
00558             if intpart is not None:
00559                 # finite number
00560                 fracpart = m.group('frac') or ''
00561                 exp = int(m.group('exp') or '0')
00562                 self._int = str(int(intpart+fracpart))
00563                 self._exp = exp - len(fracpart)
00564                 self._is_special = False
00565             else:
00566                 diag = m.group('diag')
00567                 if diag is not None:
00568                     # NaN
00569                     self._int = str(int(diag or '0')).lstrip('0')
00570                     if m.group('signal'):
00571                         self._exp = 'N'
00572                     else:
00573                         self._exp = 'n'
00574                 else:
00575                     # infinity
00576                     self._int = '0'
00577                     self._exp = 'F'
00578                 self._is_special = True
00579             return self
00580 
00581         # From an integer
00582         if isinstance(value, int):
00583             if value >= 0:
00584                 self._sign = 0
00585             else:
00586                 self._sign = 1
00587             self._exp = 0
00588             self._int = str(abs(value))
00589             self._is_special = False
00590             return self
00591 
00592         # From another decimal
00593         if isinstance(value, Decimal):
00594             self._exp  = value._exp
00595             self._sign = value._sign
00596             self._int  = value._int
00597             self._is_special  = value._is_special
00598             return self
00599 
00600         # From an internal working value
00601         if isinstance(value, _WorkRep):
00602             self._sign = value.sign
00603             self._int = str(value.int)
00604             self._exp = int(value.exp)
00605             self._is_special = False
00606             return self
00607 
00608         # tuple/list conversion (possibly from as_tuple())
00609         if isinstance(value, (list,tuple)):
00610             if len(value) != 3:
00611                 raise ValueError('Invalid tuple size in creation of Decimal '
00612                                  'from list or tuple.  The list or tuple '
00613                                  'should have exactly three elements.')
00614             # process sign.  The isinstance test rejects floats
00615             if not (isinstance(value[0], int) and value[0] in (0,1)):
00616                 raise ValueError("Invalid sign.  The first value in the tuple "
00617                                  "should be an integer; either 0 for a "
00618                                  "positive number or 1 for a negative number.")
00619             self._sign = value[0]
00620             if value[2] == 'F':
00621                 # infinity: value[1] is ignored
00622                 self._int = '0'
00623                 self._exp = value[2]
00624                 self._is_special = True
00625             else:
00626                 # process and validate the digits in value[1]
00627                 digits = []
00628                 for digit in value[1]:
00629                     if isinstance(digit, int) and 0 <= digit <= 9:
00630                         # skip leading zeros
00631                         if digits or digit != 0:
00632                             digits.append(digit)
00633                     else:
00634                         raise ValueError("The second value in the tuple must "
00635                                          "be composed of integers in the range "
00636                                          "0 through 9.")
00637                 if value[2] in ('n', 'N'):
00638                     # NaN: digits form the diagnostic
00639                     self._int = ''.join(map(str, digits))
00640                     self._exp = value[2]
00641                     self._is_special = True
00642                 elif isinstance(value[2], int):
00643                     # finite number: digits give the coefficient
00644                     self._int = ''.join(map(str, digits or [0]))
00645                     self._exp = value[2]
00646                     self._is_special = False
00647                 else:
00648                     raise ValueError("The third value in the tuple must "
00649                                      "be an integer, or one of the "
00650                                      "strings 'F', 'n', 'N'.")
00651             return self
00652 
00653         if isinstance(value, float):
00654             value = Decimal.from_float(value)
00655             self._exp  = value._exp
00656             self._sign = value._sign
00657             self._int  = value._int
00658             self._is_special  = value._is_special
00659             return self
00660 
00661         raise TypeError("Cannot convert %r to Decimal" % value)

Here is the call graph for this function:

def decimal.Decimal.__pos__ (   self,
  context = None 
)
Returns a copy, unless it is a sNaN.

Rounds the number (if more then precision digits)

Definition at line 1060 of file decimal.py.

01060 
01061     def __pos__(self, context=None):
01062         """Returns a copy, unless it is a sNaN.
01063 
01064         Rounds the number (if more then precision digits)
01065         """
01066         if self._is_special:
01067             ans = self._check_nans(context=context)
01068             if ans:
01069                 return ans
01070 
01071         if context is None:
01072             context = getcontext()
01073 
01074         if not self and context.rounding != ROUND_FLOOR:
01075             # + (-0) = 0, except in ROUND_FLOOR rounding mode.
01076             ans = self.copy_abs()
01077         else:
01078             ans = Decimal(self)
01079 
01080         return ans._fix(context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__pow__ (   self,
  other,
  modulo = None,
  context = None 
)
Return self ** other [ % modulo].

With two arguments, compute self**other.

With three arguments, compute (self**other) % modulo.  For the
three argument form, the following restrictions on the
arguments hold:

 - all three arguments must be integral
 - other must be nonnegative
 - either self or other (or both) must be nonzero
 - modulo must be nonzero and must have at most p digits,
   where p is the context precision.

If any of these restrictions is violated the InvalidOperation
flag is raised.

The result of pow(self, other, modulo) is identical to the
result that would be obtained by computing (self**other) %
modulo with unbounded precision, but is computed more
efficiently.  It is always exact.

Definition at line 2205 of file decimal.py.

02205 
02206     def __pow__(self, other, modulo=None, context=None):
02207         """Return self ** other [ % modulo].
02208 
02209         With two arguments, compute self**other.
02210 
02211         With three arguments, compute (self**other) % modulo.  For the
02212         three argument form, the following restrictions on the
02213         arguments hold:
02214 
02215          - all three arguments must be integral
02216          - other must be nonnegative
02217          - either self or other (or both) must be nonzero
02218          - modulo must be nonzero and must have at most p digits,
02219            where p is the context precision.
02220 
02221         If any of these restrictions is violated the InvalidOperation
02222         flag is raised.
02223 
02224         The result of pow(self, other, modulo) is identical to the
02225         result that would be obtained by computing (self**other) %
02226         modulo with unbounded precision, but is computed more
02227         efficiently.  It is always exact.
02228         """
02229 
02230         if modulo is not None:
02231             return self._power_modulo(other, modulo, context)
02232 
02233         other = _convert_other(other)
02234         if other is NotImplemented:
02235             return other
02236 
02237         if context is None:
02238             context = getcontext()
02239 
02240         # either argument is a NaN => result is NaN
02241         ans = self._check_nans(other, context)
02242         if ans:
02243             return ans
02244 
02245         # 0**0 = NaN (!), x**0 = 1 for nonzero x (including +/-Infinity)
02246         if not other:
02247             if not self:
02248                 return context._raise_error(InvalidOperation, '0 ** 0')
02249             else:
02250                 return _One
02251 
02252         # result has sign 1 iff self._sign is 1 and other is an odd integer
02253         result_sign = 0
02254         if self._sign == 1:
02255             if other._isinteger():
02256                 if not other._iseven():
02257                     result_sign = 1
02258             else:
02259                 # -ve**noninteger = NaN
02260                 # (-0)**noninteger = 0**noninteger
02261                 if self:
02262                     return context._raise_error(InvalidOperation,
02263                         'x ** y with x negative and y not an integer')
02264             # negate self, without doing any unwanted rounding
02265             self = self.copy_negate()
02266 
02267         # 0**(+ve or Inf)= 0; 0**(-ve or -Inf) = Infinity
02268         if not self:
02269             if other._sign == 0:
02270                 return _dec_from_triple(result_sign, '0', 0)
02271             else:
02272                 return _SignedInfinity[result_sign]
02273 
02274         # Inf**(+ve or Inf) = Inf; Inf**(-ve or -Inf) = 0
02275         if self._isinfinity():
02276             if other._sign == 0:
02277                 return _SignedInfinity[result_sign]
02278             else:
02279                 return _dec_from_triple(result_sign, '0', 0)
02280 
02281         # 1**other = 1, but the choice of exponent and the flags
02282         # depend on the exponent of self, and on whether other is a
02283         # positive integer, a negative integer, or neither
02284         if self == _One:
02285             if other._isinteger():
02286                 # exp = max(self._exp*max(int(other), 0),
02287                 # 1-context.prec) but evaluating int(other) directly
02288                 # is dangerous until we know other is small (other
02289                 # could be 1e999999999)
02290                 if other._sign == 1:
02291                     multiplier = 0
02292                 elif other > context.prec:
02293                     multiplier = context.prec
02294                 else:
02295                     multiplier = int(other)
02296 
02297                 exp = self._exp * multiplier
02298                 if exp < 1-context.prec:
02299                     exp = 1-context.prec
02300                     context._raise_error(Rounded)
02301             else:
02302                 context._raise_error(Inexact)
02303                 context._raise_error(Rounded)
02304                 exp = 1-context.prec
02305 
02306             return _dec_from_triple(result_sign, '1'+'0'*-exp, exp)
02307 
02308         # compute adjusted exponent of self
02309         self_adj = self.adjusted()
02310 
02311         # self ** infinity is infinity if self > 1, 0 if self < 1
02312         # self ** -infinity is infinity if self < 1, 0 if self > 1
02313         if other._isinfinity():
02314             if (other._sign == 0) == (self_adj < 0):
02315                 return _dec_from_triple(result_sign, '0', 0)
02316             else:
02317                 return _SignedInfinity[result_sign]
02318 
02319         # from here on, the result always goes through the call
02320         # to _fix at the end of this function.
02321         ans = None
02322         exact = False
02323 
02324         # crude test to catch cases of extreme overflow/underflow.  If
02325         # log10(self)*other >= 10**bound and bound >= len(str(Emax))
02326         # then 10**bound >= 10**len(str(Emax)) >= Emax+1 and hence
02327         # self**other >= 10**(Emax+1), so overflow occurs.  The test
02328         # for underflow is similar.
02329         bound = self._log10_exp_bound() + other.adjusted()
02330         if (self_adj >= 0) == (other._sign == 0):
02331             # self > 1 and other +ve, or self < 1 and other -ve
02332             # possibility of overflow
02333             if bound >= len(str(context.Emax)):
02334                 ans = _dec_from_triple(result_sign, '1', context.Emax+1)
02335         else:
02336             # self > 1 and other -ve, or self < 1 and other +ve
02337             # possibility of underflow to 0
02338             Etiny = context.Etiny()
02339             if bound >= len(str(-Etiny)):
02340                 ans = _dec_from_triple(result_sign, '1', Etiny-1)
02341 
02342         # try for an exact result with precision +1
02343         if ans is None:
02344             ans = self._power_exact(other, context.prec + 1)
02345             if ans is not None:
02346                 if result_sign == 1:
02347                     ans = _dec_from_triple(1, ans._int, ans._exp)
02348                 exact = True
02349 
02350         # usual case: inexact result, x**y computed directly as exp(y*log(x))
02351         if ans is None:
02352             p = context.prec
02353             x = _WorkRep(self)
02354             xc, xe = x.int, x.exp
02355             y = _WorkRep(other)
02356             yc, ye = y.int, y.exp
02357             if y.sign == 1:
02358                 yc = -yc
02359 
02360             # compute correctly rounded result:  start with precision +3,
02361             # then increase precision until result is unambiguously roundable
02362             extra = 3
02363             while True:
02364                 coeff, exp = _dpower(xc, xe, yc, ye, p+extra)
02365                 if coeff % (5*10**(len(str(coeff))-p-1)):
02366                     break
02367                 extra += 3
02368 
02369             ans = _dec_from_triple(result_sign, str(coeff), exp)
02370 
02371         # unlike exp, ln and log10, the power function respects the
02372         # rounding mode; no need to switch to ROUND_HALF_EVEN here
02373 
02374         # There's a difficulty here when 'other' is not an integer and
02375         # the result is exact.  In this case, the specification
02376         # requires that the Inexact flag be raised (in spite of
02377         # exactness), but since the result is exact _fix won't do this
02378         # for us.  (Correspondingly, the Underflow signal should also
02379         # be raised for subnormal results.)  We can't directly raise
02380         # these signals either before or after calling _fix, since
02381         # that would violate the precedence for signals.  So we wrap
02382         # the ._fix call in a temporary context, and reraise
02383         # afterwards.
02384         if exact and not other._isinteger():
02385             # pad with zeros up to length context.prec+1 if necessary; this
02386             # ensures that the Rounded signal will be raised.
02387             if len(ans._int) <= context.prec:
02388                 expdiff = context.prec + 1 - len(ans._int)
02389                 ans = _dec_from_triple(ans._sign, ans._int+'0'*expdiff,
02390                                        ans._exp-expdiff)
02391 
02392             # create a copy of the current context, with cleared flags/traps
02393             newcontext = context.copy()
02394             newcontext.clear_flags()
02395             for exception in _signals:
02396                 newcontext.traps[exception] = 0
02397 
02398             # round in the new context
02399             ans = ans._fix(newcontext)
02400 
02401             # raise Inexact, and if necessary, Underflow
02402             newcontext._raise_error(Inexact)
02403             if newcontext.flags[Subnormal]:
02404                 newcontext._raise_error(Underflow)
02405 
02406             # propagate signals to the original context; _fix could
02407             # have raised any of Overflow, Underflow, Subnormal,
02408             # Inexact, Rounded, Clamped.  Overflow needs the correct
02409             # arguments.  Note that the order of the exceptions is
02410             # important here.
02411             if newcontext.flags[Overflow]:
02412                 context._raise_error(Overflow, 'above Emax', ans._sign)
02413             for exception in Underflow, Subnormal, Inexact, Rounded, Clamped:
02414                 if newcontext.flags[exception]:
02415                     context._raise_error(exception)
02416 
02417         else:
02418             ans = ans._fix(context)
02419 
02420         return ans

Here is the call graph for this function:

def decimal.Decimal.__rdivmod__ (   self,
  other,
  context = None 
)
Swaps self/other and returns __divmod__.

Definition at line 1405 of file decimal.py.

01405 
01406     def __rdivmod__(self, other, context=None):
01407         """Swaps self/other and returns __divmod__."""
01408         other = _convert_other(other)
01409         if other is NotImplemented:
01410             return other
01411         return other.__divmod__(self, context=context)

Here is the call graph for this function:

Definition at line 3660 of file decimal.py.

03660 
03661     def __reduce__(self):
03662         return (self.__class__, (str(self),))

def decimal.Decimal.__repr__ (   self)
Represents the number as an instance of Decimal.

Definition at line 971 of file decimal.py.

00971 
00972     def __repr__(self):
00973         """Represents the number as an instance of Decimal."""
00974         # Invariant:  eval(repr(d)) == d
00975         return "Decimal('%s')" % str(self)

def decimal.Decimal.__rfloordiv__ (   self,
  other,
  context = None 
)
Swaps self/other and returns __floordiv__.

Definition at line 1549 of file decimal.py.

01549 
01550     def __rfloordiv__(self, other, context=None):
01551         """Swaps self/other and returns __floordiv__."""
01552         other = _convert_other(other)
01553         if other is NotImplemented:
01554             return other
01555         return other.__floordiv__(self, context=context)

Here is the call graph for this function:

def decimal.Decimal.__rmod__ (   self,
  other,
  context = None 
)
Swaps self/other and returns __mod__.

Definition at line 1439 of file decimal.py.

01439 
01440     def __rmod__(self, other, context=None):
01441         """Swaps self/other and returns __mod__."""
01442         other = _convert_other(other)
01443         if other is NotImplemented:
01444             return other
01445         return other.__mod__(self, context=context)

Here is the call graph for this function:

def decimal.Decimal.__round__ (   self,
  n = None 
)
Round self to the nearest integer, or to a given precision.

If only one argument is supplied, round a finite Decimal
instance self to the nearest integer.  If self is infinite or
a NaN then a Python exception is raised.  If self is finite
and lies exactly halfway between two integers then it is
rounded to the integer with even last digit.

>>> round(Decimal('123.456'))
123
>>> round(Decimal('-456.789'))
-457
>>> round(Decimal('-3.0'))
-3
>>> round(Decimal('2.5'))
2
>>> round(Decimal('3.5'))
4
>>> round(Decimal('Inf'))
Traceback (most recent call last):
  ...
OverflowError: cannot round an infinity
>>> round(Decimal('NaN'))
Traceback (most recent call last):
  ...
ValueError: cannot round a NaN

If a second argument n is supplied, self is rounded to n
decimal places using the rounding mode for the current
context.

For an integer n, round(self, -n) is exactly equivalent to
self.quantize(Decimal('1En')).

>>> round(Decimal('123.456'), 0)
Decimal('123')
>>> round(Decimal('123.456'), 2)
Decimal('123.46')
>>> round(Decimal('123.456'), -2)
Decimal('1E+2')
>>> round(Decimal('-Infinity'), 37)
Decimal('NaN')
>>> round(Decimal('sNaN123'), 0)
Decimal('NaN123')

Definition at line 1770 of file decimal.py.

01770 
01771     def __round__(self, n=None):
01772         """Round self to the nearest integer, or to a given precision.
01773 
01774         If only one argument is supplied, round a finite Decimal
01775         instance self to the nearest integer.  If self is infinite or
01776         a NaN then a Python exception is raised.  If self is finite
01777         and lies exactly halfway between two integers then it is
01778         rounded to the integer with even last digit.
01779 
01780         >>> round(Decimal('123.456'))
01781         123
01782         >>> round(Decimal('-456.789'))
01783         -457
01784         >>> round(Decimal('-3.0'))
01785         -3
01786         >>> round(Decimal('2.5'))
01787         2
01788         >>> round(Decimal('3.5'))
01789         4
01790         >>> round(Decimal('Inf'))
01791         Traceback (most recent call last):
01792           ...
01793         OverflowError: cannot round an infinity
01794         >>> round(Decimal('NaN'))
01795         Traceback (most recent call last):
01796           ...
01797         ValueError: cannot round a NaN
01798 
01799         If a second argument n is supplied, self is rounded to n
01800         decimal places using the rounding mode for the current
01801         context.
01802 
01803         For an integer n, round(self, -n) is exactly equivalent to
01804         self.quantize(Decimal('1En')).
01805 
01806         >>> round(Decimal('123.456'), 0)
01807         Decimal('123')
01808         >>> round(Decimal('123.456'), 2)
01809         Decimal('123.46')
01810         >>> round(Decimal('123.456'), -2)
01811         Decimal('1E+2')
01812         >>> round(Decimal('-Infinity'), 37)
01813         Decimal('NaN')
01814         >>> round(Decimal('sNaN123'), 0)
01815         Decimal('NaN123')
01816 
01817         """
01818         if n is not None:
01819             # two-argument form: use the equivalent quantize call
01820             if not isinstance(n, int):
01821                 raise TypeError('Second argument to round should be integral')
01822             exp = _dec_from_triple(0, '1', -n)
01823             return self.quantize(exp)
01824 
01825         # one-argument form
01826         if self._is_special:
01827             if self.is_nan():
01828                 raise ValueError("cannot round a NaN")
01829             else:
01830                 raise OverflowError("cannot round an infinity")
01831         return int(self._rescale(0, ROUND_HALF_EVEN))

Here is the call graph for this function:

def decimal.Decimal.__rpow__ (   self,
  other,
  context = None 
)
Swaps self/other and returns __pow__.

Definition at line 2421 of file decimal.py.

02421 
02422     def __rpow__(self, other, context=None):
02423         """Swaps self/other and returns __pow__."""
02424         other = _convert_other(other)
02425         if other is NotImplemented:
02426             return other
02427         return other.__pow__(self, context=context)

Here is the call graph for this function:

def decimal.Decimal.__rsub__ (   self,
  other,
  context = None 
)
Return other - self

Definition at line 1205 of file decimal.py.

01205 
01206     def __rsub__(self, other, context=None):
01207         """Return other - self"""
01208         other = _convert_other(other)
01209         if other is NotImplemented:
01210             return other
01211 
01212         return other.__sub__(self, context=context)

Here is the call graph for this function:

def decimal.Decimal.__rtruediv__ (   self,
  other,
  context = None 
)
Swaps self/other and returns __truediv__.

Definition at line 1362 of file decimal.py.

01362 
01363     def __rtruediv__(self, other, context=None):
01364         """Swaps self/other and returns __truediv__."""
01365         other = _convert_other(other)
01366         if other is NotImplemented:
01367             return other
01368         return other.__truediv__(self, context=context)

Here is the call graph for this function:

def decimal.Decimal.__str__ (   self,
  eng = False,
  context = None 
)
Return string representation of the number in scientific notation.

Captures all of the information in the underlying representation.

Definition at line 976 of file decimal.py.

00976 
00977     def __str__(self, eng=False, context=None):
00978         """Return string representation of the number in scientific notation.
00979 
00980         Captures all of the information in the underlying representation.
00981         """
00982 
00983         sign = ['', '-'][self._sign]
00984         if self._is_special:
00985             if self._exp == 'F':
00986                 return sign + 'Infinity'
00987             elif self._exp == 'n':
00988                 return sign + 'NaN' + self._int
00989             else: # self._exp == 'N'
00990                 return sign + 'sNaN' + self._int
00991 
00992         # number of digits of self._int to left of decimal point
00993         leftdigits = self._exp + len(self._int)
00994 
00995         # dotplace is number of digits of self._int to the left of the
00996         # decimal point in the mantissa of the output string (that is,
00997         # after adjusting the exponent)
00998         if self._exp <= 0 and leftdigits > -6:
00999             # no exponent required
01000             dotplace = leftdigits
01001         elif not eng:
01002             # usual scientific notation: 1 digit on left of the point
01003             dotplace = 1
01004         elif self._int == '0':
01005             # engineering notation, zero
01006             dotplace = (leftdigits + 1) % 3 - 1
01007         else:
01008             # engineering notation, nonzero
01009             dotplace = (leftdigits - 1) % 3 + 1
01010 
01011         if dotplace <= 0:
01012             intpart = '0'
01013             fracpart = '.' + '0'*(-dotplace) + self._int
01014         elif dotplace >= len(self._int):
01015             intpart = self._int+'0'*(dotplace-len(self._int))
01016             fracpart = ''
01017         else:
01018             intpart = self._int[:dotplace]
01019             fracpart = '.' + self._int[dotplace:]
01020         if leftdigits == dotplace:
01021             exp = ''
01022         else:
01023             if context is None:
01024                 context = getcontext()
01025             exp = ['e', 'E'][context.capitals] + "%+d" % (leftdigits-dotplace)
01026 
01027         return sign + intpart + fracpart + exp

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__sub__ (   self,
  other,
  context = None 
)
Return self - other

Definition at line 1191 of file decimal.py.

01191 
01192     def __sub__(self, other, context=None):
01193         """Return self - other"""
01194         other = _convert_other(other)
01195         if other is NotImplemented:
01196             return other
01197 
01198         if self._is_special or other._is_special:
01199             ans = self._check_nans(other, context=context)
01200             if ans:
01201                 return ans
01202 
01203         # self - other is computed as self + other.copy_negate()
01204         return self.__add__(other.copy_negate(), context=context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.__truediv__ (   self,
  other,
  context = None 
)
Return self / other.

Definition at line 1270 of file decimal.py.

01270 
01271     def __truediv__(self, other, context=None):
01272         """Return self / other."""
01273         other = _convert_other(other)
01274         if other is NotImplemented:
01275             return NotImplemented
01276 
01277         if context is None:
01278             context = getcontext()
01279 
01280         sign = self._sign ^ other._sign
01281 
01282         if self._is_special or other._is_special:
01283             ans = self._check_nans(other, context)
01284             if ans:
01285                 return ans
01286 
01287             if self._isinfinity() and other._isinfinity():
01288                 return context._raise_error(InvalidOperation, '(+-)INF/(+-)INF')
01289 
01290             if self._isinfinity():
01291                 return _SignedInfinity[sign]
01292 
01293             if other._isinfinity():
01294                 context._raise_error(Clamped, 'Division by infinity')
01295                 return _dec_from_triple(sign, '0', context.Etiny())
01296 
01297         # Special cases for zeroes
01298         if not other:
01299             if not self:
01300                 return context._raise_error(DivisionUndefined, '0 / 0')
01301             return context._raise_error(DivisionByZero, 'x / 0', sign)
01302 
01303         if not self:
01304             exp = self._exp - other._exp
01305             coeff = 0
01306         else:
01307             # OK, so neither = 0, INF or NaN
01308             shift = len(other._int) - len(self._int) + context.prec + 1
01309             exp = self._exp - other._exp - shift
01310             op1 = _WorkRep(self)
01311             op2 = _WorkRep(other)
01312             if shift >= 0:
01313                 coeff, remainder = divmod(op1.int * 10**shift, op2.int)
01314             else:
01315                 coeff, remainder = divmod(op1.int, op2.int * 10**-shift)
01316             if remainder:
01317                 # result is not exact; adjust to ensure correct rounding
01318                 if coeff % 5 == 0:
01319                     coeff += 1
01320             else:
01321                 # result is exact; get as close to ideal exponent as possible
01322                 ideal_exp = self._exp - other._exp
01323                 while exp < ideal_exp and coeff % 10 == 0:
01324                     coeff //= 10
01325                     exp += 1
01326 
01327         ans = _dec_from_triple(sign, str(coeff), exp)
01328         return ans._fix(context)

Here is the call graph for this function:

def decimal.Decimal._check_nans (   self,
  other = None,
  context = None 
) [private]
Returns whether the number is not actually one.

if self, other are sNaN, signal
if self, other are NaN return nan
return 0

Done before operations.

Definition at line 730 of file decimal.py.

00730 
00731     def _check_nans(self, other=None, context=None):
00732         """Returns whether the number is not actually one.
00733 
00734         if self, other are sNaN, signal
00735         if self, other are NaN return nan
00736         return 0
00737 
00738         Done before operations.
00739         """
00740 
00741         self_is_nan = self._isnan()
00742         if other is None:
00743             other_is_nan = False
00744         else:
00745             other_is_nan = other._isnan()
00746 
00747         if self_is_nan or other_is_nan:
00748             if context is None:
00749                 context = getcontext()
00750 
00751             if self_is_nan == 2:
00752                 return context._raise_error(InvalidOperation, 'sNaN',
00753                                         self)
00754             if other_is_nan == 2:
00755                 return context._raise_error(InvalidOperation, 'sNaN',
00756                                         other)
00757             if self_is_nan:
00758                 return self._fix_nan(context)
00759 
00760             return other._fix_nan(context)
00761         return 0

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._cmp (   self,
  other 
) [private]
Compare the two non-NaN decimal instances self and other.

Returns -1 if self < other, 0 if self == other and 1
if self > other.  This routine is for internal use only.

Definition at line 802 of file decimal.py.

00802 
00803     def _cmp(self, other):
00804         """Compare the two non-NaN decimal instances self and other.
00805 
00806         Returns -1 if self < other, 0 if self == other and 1
00807         if self > other.  This routine is for internal use only."""
00808 
00809         if self._is_special or other._is_special:
00810             self_inf = self._isinfinity()
00811             other_inf = other._isinfinity()
00812             if self_inf == other_inf:
00813                 return 0
00814             elif self_inf < other_inf:
00815                 return -1
00816             else:
00817                 return 1
00818 
00819         # check for zeros;  Decimal('0') == Decimal('-0')
00820         if not self:
00821             if not other:
00822                 return 0
00823             else:
00824                 return -((-1)**other._sign)
00825         if not other:
00826             return (-1)**self._sign
00827 
00828         # If different signs, neg one is less
00829         if other._sign < self._sign:
00830             return -1
00831         if self._sign < other._sign:
00832             return 1
00833 
00834         self_adjusted = self.adjusted()
00835         other_adjusted = other.adjusted()
00836         if self_adjusted == other_adjusted:
00837             self_padded = self._int + '0'*(self._exp - other._exp)
00838             other_padded = other._int + '0'*(other._exp - self._exp)
00839             if self_padded == other_padded:
00840                 return 0
00841             elif self_padded < other_padded:
00842                 return -(-1)**self._sign
00843             else:
00844                 return (-1)**self._sign
00845         elif self_adjusted > other_adjusted:
00846             return (-1)**self._sign
00847         else: # self_adjusted < other_adjusted
00848             return -((-1)**self._sign)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._compare_check_nans (   self,
  other,
  context 
) [private]
Version of _check_nans used for the signaling comparisons
compare_signal, __le__, __lt__, __ge__, __gt__.

Signal InvalidOperation if either self or other is a (quiet
or signaling) NaN.  Signaling NaNs take precedence over quiet
NaNs.

Return 0 if neither operand is a NaN.

Definition at line 762 of file decimal.py.

00762 
00763     def _compare_check_nans(self, other, context):
00764         """Version of _check_nans used for the signaling comparisons
00765         compare_signal, __le__, __lt__, __ge__, __gt__.
00766 
00767         Signal InvalidOperation if either self or other is a (quiet
00768         or signaling) NaN.  Signaling NaNs take precedence over quiet
00769         NaNs.
00770 
00771         Return 0 if neither operand is a NaN.
00772 
00773         """
00774         if context is None:
00775             context = getcontext()
00776 
00777         if self._is_special or other._is_special:
00778             if self.is_snan():
00779                 return context._raise_error(InvalidOperation,
00780                                             'comparison involving sNaN',
00781                                             self)
00782             elif other.is_snan():
00783                 return context._raise_error(InvalidOperation,
00784                                             'comparison involving sNaN',
00785                                             other)
00786             elif self.is_qnan():
00787                 return context._raise_error(InvalidOperation,
00788                                             'comparison involving NaN',
00789                                             self)
00790             elif other.is_qnan():
00791                 return context._raise_error(InvalidOperation,
00792                                             'comparison involving NaN',
00793                                             other)
00794         return 0

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._divide (   self,
  other,
  context 
) [private]
Return (self // other, self % other), to context.prec precision.

Assumes that neither self nor other is a NaN, that self is not
infinite and that other is nonzero.

Definition at line 1329 of file decimal.py.

01329 
01330     def _divide(self, other, context):
01331         """Return (self // other, self % other), to context.prec precision.
01332 
01333         Assumes that neither self nor other is a NaN, that self is not
01334         infinite and that other is nonzero.
01335         """
01336         sign = self._sign ^ other._sign
01337         if other._isinfinity():
01338             ideal_exp = self._exp
01339         else:
01340             ideal_exp = min(self._exp, other._exp)
01341 
01342         expdiff = self.adjusted() - other.adjusted()
01343         if not self or other._isinfinity() or expdiff <= -2:
01344             return (_dec_from_triple(sign, '0', 0),
01345                     self._rescale(ideal_exp, context.rounding))
01346         if expdiff <= context.prec:
01347             op1 = _WorkRep(self)
01348             op2 = _WorkRep(other)
01349             if op1.exp >= op2.exp:
01350                 op1.int *= 10**(op1.exp - op2.exp)
01351             else:
01352                 op2.int *= 10**(op2.exp - op1.exp)
01353             q, r = divmod(op1.int, op2.int)
01354             if q < 10**context.prec:
01355                 return (_dec_from_triple(sign, str(q), 0),
01356                         _dec_from_triple(self._sign, str(r), ideal_exp))
01357 
01358         # Here the quotient is too large to be representable
01359         ans = context._raise_error(DivisionImpossible,
01360                                    'quotient too large in //, % or divmod')
01361         return ans, ans

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._fill_logical (   self,
  context,
  opa,
  opb 
) [private]

Definition at line 3294 of file decimal.py.

03294 
03295     def _fill_logical(self, context, opa, opb):
03296         dif = context.prec - len(opa)
03297         if dif > 0:
03298             opa = '0'*dif + opa
03299         elif dif < 0:
03300             opa = opa[-context.prec:]
03301         dif = context.prec - len(opb)
03302         if dif > 0:
03303             opb = '0'*dif + opb
03304         elif dif < 0:
03305             opb = opb[-context.prec:]
03306         return opa, opb

Here is the caller graph for this function:

def decimal.Decimal._fix (   self,
  context 
) [private]
Round if it is necessary to keep self within prec precision.

Rounds and fixes the exponent.  Does not raise on a sNaN.

Arguments:
self - Decimal instance
context - context used.

Definition at line 1601 of file decimal.py.

01601 
01602     def _fix(self, context):
01603         """Round if it is necessary to keep self within prec precision.
01604 
01605         Rounds and fixes the exponent.  Does not raise on a sNaN.
01606 
01607         Arguments:
01608         self - Decimal instance
01609         context - context used.
01610         """
01611 
01612         if self._is_special:
01613             if self._isnan():
01614                 # decapitate payload if necessary
01615                 return self._fix_nan(context)
01616             else:
01617                 # self is +/-Infinity; return unaltered
01618                 return Decimal(self)
01619 
01620         # if self is zero then exponent should be between Etiny and
01621         # Emax if clamp==0, and between Etiny and Etop if clamp==1.
01622         Etiny = context.Etiny()
01623         Etop = context.Etop()
01624         if not self:
01625             exp_max = [context.Emax, Etop][context.clamp]
01626             new_exp = min(max(self._exp, Etiny), exp_max)
01627             if new_exp != self._exp:
01628                 context._raise_error(Clamped)
01629                 return _dec_from_triple(self._sign, '0', new_exp)
01630             else:
01631                 return Decimal(self)
01632 
01633         # exp_min is the smallest allowable exponent of the result,
01634         # equal to max(self.adjusted()-context.prec+1, Etiny)
01635         exp_min = len(self._int) + self._exp - context.prec
01636         if exp_min > Etop:
01637             # overflow: exp_min > Etop iff self.adjusted() > Emax
01638             ans = context._raise_error(Overflow, 'above Emax', self._sign)
01639             context._raise_error(Inexact)
01640             context._raise_error(Rounded)
01641             return ans
01642 
01643         self_is_subnormal = exp_min < Etiny
01644         if self_is_subnormal:
01645             exp_min = Etiny
01646 
01647         # round if self has too many digits
01648         if self._exp < exp_min:
01649             digits = len(self._int) + self._exp - exp_min
01650             if digits < 0:
01651                 self = _dec_from_triple(self._sign, '1', exp_min-1)
01652                 digits = 0
01653             rounding_method = self._pick_rounding_function[context.rounding]
01654             changed = rounding_method(self, digits)
01655             coeff = self._int[:digits] or '0'
01656             if changed > 0:
01657                 coeff = str(int(coeff)+1)
01658                 if len(coeff) > context.prec:
01659                     coeff = coeff[:-1]
01660                     exp_min += 1
01661 
01662             # check whether the rounding pushed the exponent out of range
01663             if exp_min > Etop:
01664                 ans = context._raise_error(Overflow, 'above Emax', self._sign)
01665             else:
01666                 ans = _dec_from_triple(self._sign, coeff, exp_min)
01667 
01668             # raise the appropriate signals, taking care to respect
01669             # the precedence described in the specification
01670             if changed and self_is_subnormal:
01671                 context._raise_error(Underflow)
01672             if self_is_subnormal:
01673                 context._raise_error(Subnormal)
01674             if changed:
01675                 context._raise_error(Inexact)
01676             context._raise_error(Rounded)
01677             if not ans:
01678                 # raise Clamped on underflow to 0
01679                 context._raise_error(Clamped)
01680             return ans
01681 
01682         if self_is_subnormal:
01683             context._raise_error(Subnormal)
01684 
01685         # fold down if clamp == 1 and self has too few digits
01686         if context.clamp == 1 and self._exp > Etop:
01687             context._raise_error(Clamped)
01688             self_padded = self._int + '0'*(self._exp - Etop)
01689             return _dec_from_triple(self._sign, self_padded, Etop)
01690 
01691         # here self was representable to begin with; return unchanged
01692         return Decimal(self)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._fix_nan (   self,
  context 
) [private]
Decapitate the payload of a NaN to fit the context

Definition at line 1589 of file decimal.py.

01589 
01590     def _fix_nan(self, context):
01591         """Decapitate the payload of a NaN to fit the context"""
01592         payload = self._int
01593 
01594         # maximum length of payload is precision if clamp=0,
01595         # precision-1 if clamp=1.
01596         max_payload_len = context.prec - context.clamp
01597         if len(payload) > max_payload_len:
01598             payload = payload[len(payload)-max_payload_len:].lstrip('0')
01599             return _dec_from_triple(self._sign, payload, self._exp, True)
01600         return Decimal(self)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._iseven (   self) [private]
Returns True if self is even.  Assumes self is an integer.

Definition at line 2828 of file decimal.py.

02828 
02829     def _iseven(self):
02830         """Returns True if self is even.  Assumes self is an integer."""
02831         if not self or self._exp > 0:
02832             return True
02833         return self._int[-1+self._exp] in '02468'

def decimal.Decimal._isinfinity (   self) [private]
Returns whether the number is infinite

0 if finite or not a number
1 if +INF
-1 if -INF

Definition at line 717 of file decimal.py.

00717 
00718     def _isinfinity(self):
00719         """Returns whether the number is infinite
00720 
00721         0 if finite or not a number
00722         1 if +INF
00723         -1 if -INF
00724         """
00725         if self._exp == 'F':
00726             if self._sign:
00727                 return -1
00728             return 1
00729         return 0

Here is the caller graph for this function:

def decimal.Decimal._isinteger (   self) [private]
Returns whether self is an integer

Definition at line 2819 of file decimal.py.

02819 
02820     def _isinteger(self):
02821         """Returns whether self is an integer"""
02822         if self._is_special:
02823             return False
02824         if self._exp >= 0:
02825             return True
02826         rest = self._int[self._exp:]
02827         return rest == '0'*len(rest)

Here is the caller graph for this function:

def decimal.Decimal._islogical (   self) [private]
Return True if self is a logical operand.

For being logical, it must be a finite number with a sign of 0,
an exponent of 0, and a coefficient whose digits must all be
either 0 or 1.

Definition at line 3280 of file decimal.py.

03280 
03281     def _islogical(self):
03282         """Return True if self is a logical operand.
03283 
03284         For being logical, it must be a finite number with a sign of 0,
03285         an exponent of 0, and a coefficient whose digits must all be
03286         either 0 or 1.
03287         """
03288         if self._sign != 0 or self._exp != 0:
03289             return False
03290         for dig in self._int:
03291             if dig not in '01':
03292                 return False
03293         return True

Here is the caller graph for this function:

def decimal.Decimal._isnan (   self) [private]
Returns whether the number is not actually one.

0 if a number
1 if NaN
2 if sNaN

Definition at line 702 of file decimal.py.

00702 
00703     def _isnan(self):
00704         """Returns whether the number is not actually one.
00705 
00706         0 if a number
00707         1 if NaN
00708         2 if sNaN
00709         """
00710         if self._is_special:
00711             exp = self._exp
00712             if exp == 'n':
00713                 return 1
00714             elif exp == 'N':
00715                 return 2
00716         return 0

Here is the caller graph for this function:

def decimal.Decimal._ln_exp_bound (   self) [private]
Compute a lower bound for the adjusted exponent of self.ln().
In other words, compute r such that self.ln() >= 10**r.  Assumes
that self is finite and positive and that self != 1.

Definition at line 3094 of file decimal.py.

03094 
03095     def _ln_exp_bound(self):
03096         """Compute a lower bound for the adjusted exponent of self.ln().
03097         In other words, compute r such that self.ln() >= 10**r.  Assumes
03098         that self is finite and positive and that self != 1.
03099         """
03100 
03101         # for 0.1 <= x <= 10 we use the inequalities 1-1/x <= ln(x) <= x-1
03102         adj = self._exp + len(self._int) - 1
03103         if adj >= 1:
03104             # argument >= 10; we use 23/10 = 2.3 as a lower bound for ln(10)
03105             return len(str(adj*23//10)) - 1
03106         if adj <= -2:
03107             # argument <= 0.1
03108             return len(str((-1-adj)*23//10)) - 1
03109         op = _WorkRep(self)
03110         c, e = op.int, op.exp
03111         if adj == 0:
03112             # 1 < self < 10
03113             num = str(c-10**-e)
03114             den = str(c)
03115             return len(num) - len(den) - (num < den)
03116         # adj == -1, 0.1 <= self < 1
03117         return e + len(str(10**-e - c)) - 1
03118 

Here is the caller graph for this function:

def decimal.Decimal._log10_exp_bound (   self) [private]
Compute a lower bound for the adjusted exponent of self.log10().
In other words, find r such that self.log10() >= 10**r.
Assumes that self is finite and positive and that self != 1.

Definition at line 3169 of file decimal.py.

03169 
03170     def _log10_exp_bound(self):
03171         """Compute a lower bound for the adjusted exponent of self.log10().
03172         In other words, find r such that self.log10() >= 10**r.
03173         Assumes that self is finite and positive and that self != 1.
03174         """
03175 
03176         # For x >= 10 or x < 0.1 we only need a bound on the integer
03177         # part of log10(self), and this comes directly from the
03178         # exponent of x.  For 0.1 <= x <= 10 we use the inequalities
03179         # 1-1/x <= log(x) <= x-1. If x > 1 we have |log10(x)| >
03180         # (1-1/x)/2.31 > 0.  If x < 1 then |log10(x)| > (1-x)/2.31 > 0
03181 
03182         adj = self._exp + len(self._int) - 1
03183         if adj >= 1:
03184             # self >= 10
03185             return len(str(adj))-1
03186         if adj <= -2:
03187             # self < 0.1
03188             return len(str(-1-adj))-1
03189         op = _WorkRep(self)
03190         c, e = op.int, op.exp
03191         if adj == 0:
03192             # 1 < self < 10
03193             num = str(c-10**-e)
03194             den = str(231*c)
03195             return len(num) - len(den) - (num < den) + 2
03196         # adj == -1, 0.1 <= self < 1
03197         num = str(10**-e-c)
03198         return len(num) + e - (num < "231") - 1

Here is the caller graph for this function:

def decimal.Decimal._power_exact (   self,
  other,
  p 
) [private]
Attempt to compute self**other exactly.

Given Decimals self and other and an integer p, attempt to
compute an exact result for the power self**other, with p
digits of precision.  Return None if self**other is not
exactly representable in p digits.

Assumes that elimination of special cases has already been
performed: self and other must both be nonspecial; self must
be positive and not numerically equal to 1; other must be
nonzero.  For efficiency, other._exp should not be too large,
so that 10**abs(other._exp) is a feasible calculation.

Definition at line 1990 of file decimal.py.

01990 
01991     def _power_exact(self, other, p):
01992         """Attempt to compute self**other exactly.
01993 
01994         Given Decimals self and other and an integer p, attempt to
01995         compute an exact result for the power self**other, with p
01996         digits of precision.  Return None if self**other is not
01997         exactly representable in p digits.
01998 
01999         Assumes that elimination of special cases has already been
02000         performed: self and other must both be nonspecial; self must
02001         be positive and not numerically equal to 1; other must be
02002         nonzero.  For efficiency, other._exp should not be too large,
02003         so that 10**abs(other._exp) is a feasible calculation."""
02004 
02005         # In the comments below, we write x for the value of self and
02006         # y for the value of other.  Write x = xc*10**xe and y =
02007         # yc*10**ye.
02008 
02009         # The main purpose of this method is to identify the *failure*
02010         # of x**y to be exactly representable with as little effort as
02011         # possible.  So we look for cheap and easy tests that
02012         # eliminate the possibility of x**y being exact.  Only if all
02013         # these tests are passed do we go on to actually compute x**y.
02014 
02015         # Here's the main idea.  First normalize both x and y.  We
02016         # express y as a rational m/n, with m and n relatively prime
02017         # and n>0.  Then for x**y to be exactly representable (at
02018         # *any* precision), xc must be the nth power of a positive
02019         # integer and xe must be divisible by n.  If m is negative
02020         # then additionally xc must be a power of either 2 or 5, hence
02021         # a power of 2**n or 5**n.
02022         #
02023         # There's a limit to how small |y| can be: if y=m/n as above
02024         # then:
02025         #
02026         #  (1) if xc != 1 then for the result to be representable we
02027         #      need xc**(1/n) >= 2, and hence also xc**|y| >= 2.  So
02028         #      if |y| <= 1/nbits(xc) then xc < 2**nbits(xc) <=
02029         #      2**(1/|y|), hence xc**|y| < 2 and the result is not
02030         #      representable.
02031         #
02032         #  (2) if xe != 0, |xe|*(1/n) >= 1, so |xe|*|y| >= 1.  Hence if
02033         #      |y| < 1/|xe| then the result is not representable.
02034         #
02035         # Note that since x is not equal to 1, at least one of (1) and
02036         # (2) must apply.  Now |y| < 1/nbits(xc) iff |yc|*nbits(xc) <
02037         # 10**-ye iff len(str(|yc|*nbits(xc)) <= -ye.
02038         #
02039         # There's also a limit to how large y can be, at least if it's
02040         # positive: the normalized result will have coefficient xc**y,
02041         # so if it's representable then xc**y < 10**p, and y <
02042         # p/log10(xc).  Hence if y*log10(xc) >= p then the result is
02043         # not exactly representable.
02044 
02045         # if len(str(abs(yc*xe)) <= -ye then abs(yc*xe) < 10**-ye,
02046         # so |y| < 1/xe and the result is not representable.
02047         # Similarly, len(str(abs(yc)*xc_bits)) <= -ye implies |y|
02048         # < 1/nbits(xc).
02049 
02050         x = _WorkRep(self)
02051         xc, xe = x.int, x.exp
02052         while xc % 10 == 0:
02053             xc //= 10
02054             xe += 1
02055 
02056         y = _WorkRep(other)
02057         yc, ye = y.int, y.exp
02058         while yc % 10 == 0:
02059             yc //= 10
02060             ye += 1
02061 
02062         # case where xc == 1: result is 10**(xe*y), with xe*y
02063         # required to be an integer
02064         if xc == 1:
02065             xe *= yc
02066             # result is now 10**(xe * 10**ye);  xe * 10**ye must be integral
02067             while xe % 10 == 0:
02068                 xe //= 10
02069                 ye += 1
02070             if ye < 0:
02071                 return None
02072             exponent = xe * 10**ye
02073             if y.sign == 1:
02074                 exponent = -exponent
02075             # if other is a nonnegative integer, use ideal exponent
02076             if other._isinteger() and other._sign == 0:
02077                 ideal_exponent = self._exp*int(other)
02078                 zeros = min(exponent-ideal_exponent, p-1)
02079             else:
02080                 zeros = 0
02081             return _dec_from_triple(0, '1' + '0'*zeros, exponent-zeros)
02082 
02083         # case where y is negative: xc must be either a power
02084         # of 2 or a power of 5.
02085         if y.sign == 1:
02086             last_digit = xc % 10
02087             if last_digit in (2,4,6,8):
02088                 # quick test for power of 2
02089                 if xc & -xc != xc:
02090                     return None
02091                 # now xc is a power of 2; e is its exponent
02092                 e = _nbits(xc)-1
02093                 # find e*y and xe*y; both must be integers
02094                 if ye >= 0:
02095                     y_as_int = yc*10**ye
02096                     e = e*y_as_int
02097                     xe = xe*y_as_int
02098                 else:
02099                     ten_pow = 10**-ye
02100                     e, remainder = divmod(e*yc, ten_pow)
02101                     if remainder:
02102                         return None
02103                     xe, remainder = divmod(xe*yc, ten_pow)
02104                     if remainder:
02105                         return None
02106 
02107                 if e*65 >= p*93: # 93/65 > log(10)/log(5)
02108                     return None
02109                 xc = 5**e
02110 
02111             elif last_digit == 5:
02112                 # e >= log_5(xc) if xc is a power of 5; we have
02113                 # equality all the way up to xc=5**2658
02114                 e = _nbits(xc)*28//65
02115                 xc, remainder = divmod(5**e, xc)
02116                 if remainder:
02117                     return None
02118                 while xc % 5 == 0:
02119                     xc //= 5
02120                     e -= 1
02121                 if ye >= 0:
02122                     y_as_integer = yc*10**ye
02123                     e = e*y_as_integer
02124                     xe = xe*y_as_integer
02125                 else:
02126                     ten_pow = 10**-ye
02127                     e, remainder = divmod(e*yc, ten_pow)
02128                     if remainder:
02129                         return None
02130                     xe, remainder = divmod(xe*yc, ten_pow)
02131                     if remainder:
02132                         return None
02133                 if e*3 >= p*10: # 10/3 > log(10)/log(2)
02134                     return None
02135                 xc = 2**e
02136             else:
02137                 return None
02138 
02139             if xc >= 10**p:
02140                 return None
02141             xe = -e-xe
02142             return _dec_from_triple(0, str(xc), xe)
02143 
02144         # now y is positive; find m and n such that y = m/n
02145         if ye >= 0:
02146             m, n = yc*10**ye, 1
02147         else:
02148             if xe != 0 and len(str(abs(yc*xe))) <= -ye:
02149                 return None
02150             xc_bits = _nbits(xc)
02151             if xc != 1 and len(str(abs(yc)*xc_bits)) <= -ye:
02152                 return None
02153             m, n = yc, 10**(-ye)
02154             while m % 2 == n % 2 == 0:
02155                 m //= 2
02156                 n //= 2
02157             while m % 5 == n % 5 == 0:
02158                 m //= 5
02159                 n //= 5
02160 
02161         # compute nth root of xc*10**xe
02162         if n > 1:
02163             # if 1 < xc < 2**n then xc isn't an nth power
02164             if xc != 1 and xc_bits <= n:
02165                 return None
02166 
02167             xe, rem = divmod(xe, n)
02168             if rem != 0:
02169                 return None
02170 
02171             # compute nth root of xc using Newton's method
02172             a = 1 << -(-_nbits(xc)//n) # initial estimate
02173             while True:
02174                 q, r = divmod(xc, a**(n-1))
02175                 if a <= q:
02176                     break
02177                 else:
02178                     a = (a*(n-1) + q)//n
02179             if not (a == q and r == 0):
02180                 return None
02181             xc = a
02182 
02183         # now xc*10**xe is the nth root of the original xc*10**xe
02184         # compute mth power of xc*10**xe
02185 
02186         # if m > p*100//_log10_lb(xc) then m > p/log10(xc), hence xc**m >
02187         # 10**p and the result is not representable.
02188         if xc > 1 and m > p*100//_log10_lb(xc):
02189             return None
02190         xc = xc**m
02191         xe *= m
02192         if xc > 10**p:
02193             return None
02194 
02195         # by this point the result *is* exactly representable
02196         # adjust the exponent to get as close as possible to the ideal
02197         # exponent, if necessary
02198         str_xc = str(xc)
02199         if other._isinteger() and other._sign == 0:
02200             ideal_exponent = self._exp*int(other)
02201             zeros = min(xe-ideal_exponent, p-len(str_xc))
02202         else:
02203             zeros = 0
02204         return _dec_from_triple(0, str_xc+'0'*zeros, xe-zeros)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._power_modulo (   self,
  other,
  modulo,
  context = None 
) [private]
Three argument version of __pow__

Definition at line 1906 of file decimal.py.

01906 
01907     def _power_modulo(self, other, modulo, context=None):
01908         """Three argument version of __pow__"""
01909 
01910         # if can't convert other and modulo to Decimal, raise
01911         # TypeError; there's no point returning NotImplemented (no
01912         # equivalent of __rpow__ for three argument pow)
01913         other = _convert_other(other, raiseit=True)
01914         modulo = _convert_other(modulo, raiseit=True)
01915 
01916         if context is None:
01917             context = getcontext()
01918 
01919         # deal with NaNs: if there are any sNaNs then first one wins,
01920         # (i.e. behaviour for NaNs is identical to that of fma)
01921         self_is_nan = self._isnan()
01922         other_is_nan = other._isnan()
01923         modulo_is_nan = modulo._isnan()
01924         if self_is_nan or other_is_nan or modulo_is_nan:
01925             if self_is_nan == 2:
01926                 return context._raise_error(InvalidOperation, 'sNaN',
01927                                         self)
01928             if other_is_nan == 2:
01929                 return context._raise_error(InvalidOperation, 'sNaN',
01930                                         other)
01931             if modulo_is_nan == 2:
01932                 return context._raise_error(InvalidOperation, 'sNaN',
01933                                         modulo)
01934             if self_is_nan:
01935                 return self._fix_nan(context)
01936             if other_is_nan:
01937                 return other._fix_nan(context)
01938             return modulo._fix_nan(context)
01939 
01940         # check inputs: we apply same restrictions as Python's pow()
01941         if not (self._isinteger() and
01942                 other._isinteger() and
01943                 modulo._isinteger()):
01944             return context._raise_error(InvalidOperation,
01945                                         'pow() 3rd argument not allowed '
01946                                         'unless all arguments are integers')
01947         if other < 0:
01948             return context._raise_error(InvalidOperation,
01949                                         'pow() 2nd argument cannot be '
01950                                         'negative when 3rd argument specified')
01951         if not modulo:
01952             return context._raise_error(InvalidOperation,
01953                                         'pow() 3rd argument cannot be 0')
01954 
01955         # additional restriction for decimal: the modulus must be less
01956         # than 10**prec in absolute value
01957         if modulo.adjusted() >= context.prec:
01958             return context._raise_error(InvalidOperation,
01959                                         'insufficient precision: pow() 3rd '
01960                                         'argument must not have more than '
01961                                         'precision digits')
01962 
01963         # define 0**0 == NaN, for consistency with two-argument pow
01964         # (even though it hurts!)
01965         if not other and not self:
01966             return context._raise_error(InvalidOperation,
01967                                         'at least one of pow() 1st argument '
01968                                         'and 2nd argument must be nonzero ;'
01969                                         '0**0 is not defined')
01970 
01971         # compute sign of result
01972         if other._iseven():
01973             sign = 0
01974         else:
01975             sign = self._sign
01976 
01977         # convert modulo to a Python integer, and self and other to
01978         # Decimal integers (i.e. force their exponents to be >= 0)
01979         modulo = abs(int(modulo))
01980         base = _WorkRep(self.to_integral_value())
01981         exponent = _WorkRep(other.to_integral_value())
01982 
01983         # compute result using integer pow()
01984         base = (base.int % modulo * pow(10, base.exp, modulo)) % modulo
01985         for i in range(exponent.exp):
01986             base = pow(base, 10, modulo)
01987         base = pow(base, exponent.int, modulo)
01988 
01989         return _dec_from_triple(sign, str(base), 0)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._rescale (   self,
  exp,
  rounding 
) [private]
Rescale self so that the exponent is exp, either by padding with zeros
or by truncating digits, using the given rounding mode.

Specials are returned without change.  This operation is
quiet: it raises no flags, and uses no information from the
context.

exp = exp to scale to (an integer)
rounding = rounding mode

Definition at line 2539 of file decimal.py.

02539 
02540     def _rescale(self, exp, rounding):
02541         """Rescale self so that the exponent is exp, either by padding with zeros
02542         or by truncating digits, using the given rounding mode.
02543 
02544         Specials are returned without change.  This operation is
02545         quiet: it raises no flags, and uses no information from the
02546         context.
02547 
02548         exp = exp to scale to (an integer)
02549         rounding = rounding mode
02550         """
02551         if self._is_special:
02552             return Decimal(self)
02553         if not self:
02554             return _dec_from_triple(self._sign, '0', exp)
02555 
02556         if self._exp >= exp:
02557             # pad answer with zeros if necessary
02558             return _dec_from_triple(self._sign,
02559                                         self._int + '0'*(self._exp - exp), exp)
02560 
02561         # too many digits; round and lose data.  If self.adjusted() <
02562         # exp-1, replace self by 10**(exp-1) before rounding
02563         digits = len(self._int) + self._exp - exp
02564         if digits < 0:
02565             self = _dec_from_triple(self._sign, '1', exp-1)
02566             digits = 0
02567         this_function = self._pick_rounding_function[rounding]
02568         changed = this_function(self, digits)
02569         coeff = self._int[:digits] or '0'
02570         if changed == 1:
02571             coeff = str(int(coeff)+1)
02572         return _dec_from_triple(self._sign, coeff, exp)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._round (   self,
  places,
  rounding 
) [private]
Round a nonzero, nonspecial Decimal to a fixed number of
significant figures, using the given rounding mode.

Infinities, NaNs and zeros are returned unaltered.

This operation is quiet: it raises no flags, and uses no
information from the context.

Definition at line 2573 of file decimal.py.

02573 
02574     def _round(self, places, rounding):
02575         """Round a nonzero, nonspecial Decimal to a fixed number of
02576         significant figures, using the given rounding mode.
02577 
02578         Infinities, NaNs and zeros are returned unaltered.
02579 
02580         This operation is quiet: it raises no flags, and uses no
02581         information from the context.
02582 
02583         """
02584         if places <= 0:
02585             raise ValueError("argument should be at least 1 in _round")
02586         if self._is_special or not self:
02587             return Decimal(self)
02588         ans = self._rescale(self.adjusted()+1-places, rounding)
02589         # it can happen that the rescale alters the adjusted exponent;
02590         # for example when rounding 99.97 to 3 significant figures.
02591         # When this happens we end up with an extra 0 at the end of
02592         # the number; a second rescale fixes this.
02593         if ans.adjusted() != self.adjusted():
02594             ans = ans._rescale(ans.adjusted()+1-places, rounding)
02595         return ans

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal._round_05up (   self,
  prec 
) [private]
Round down unless digit prec-1 is 0 or 5.

Definition at line 1752 of file decimal.py.

01752 
01753     def _round_05up(self, prec):
01754         """Round down unless digit prec-1 is 0 or 5."""
01755         if prec and self._int[prec-1] not in '05':
01756             return self._round_down(prec)
01757         else:
01758             return -self._round_down(prec)

Here is the call graph for this function:

def decimal.Decimal._round_ceiling (   self,
  prec 
) [private]
Rounds up (not away from 0 if negative.)

Definition at line 1738 of file decimal.py.

01738 
01739     def _round_ceiling(self, prec):
01740         """Rounds up (not away from 0 if negative.)"""
01741         if self._sign:
01742             return self._round_down(prec)
01743         else:
01744             return -self._round_down(prec)

Here is the call graph for this function:

def decimal.Decimal._round_down (   self,
  prec 
) [private]
Also known as round-towards-0, truncate.

Definition at line 1703 of file decimal.py.

01703 
01704     def _round_down(self, prec):
01705         """Also known as round-towards-0, truncate."""
01706         if _all_zeros(self._int, prec):
01707             return 0
01708         else:
01709             return -1

Here is the caller graph for this function:

def decimal.Decimal._round_floor (   self,
  prec 
) [private]
Rounds down (not towards 0 if negative)

Definition at line 1745 of file decimal.py.

01745 
01746     def _round_floor(self, prec):
01747         """Rounds down (not towards 0 if negative)"""
01748         if not self._sign:
01749             return self._round_down(prec)
01750         else:
01751             return -self._round_down(prec)

Here is the call graph for this function:

def decimal.Decimal._round_half_down (   self,
  prec 
) [private]
Round 5 down

Definition at line 1723 of file decimal.py.

01723 
01724     def _round_half_down(self, prec):
01725         """Round 5 down"""
01726         if _exact_half(self._int, prec):
01727             return -1
01728         else:
01729             return self._round_half_up(prec)

Here is the call graph for this function:

def decimal.Decimal._round_half_even (   self,
  prec 
) [private]
Round 5 to even, rest to nearest.

Definition at line 1730 of file decimal.py.

01730 
01731     def _round_half_even(self, prec):
01732         """Round 5 to even, rest to nearest."""
01733         if _exact_half(self._int, prec) and \
01734                 (prec == 0 or self._int[prec-1] in '02468'):
01735             return -1
01736         else:
01737             return self._round_half_up(prec)

Here is the call graph for this function:

def decimal.Decimal._round_half_up (   self,
  prec 
) [private]
Rounds 5 up (away from 0)

Definition at line 1714 of file decimal.py.

01714 
01715     def _round_half_up(self, prec):
01716         """Rounds 5 up (away from 0)"""
01717         if self._int[prec] in '56789':
01718             return 1
01719         elif _all_zeros(self._int, prec):
01720             return 0
01721         else:
01722             return -1

Here is the caller graph for this function:

def decimal.Decimal._round_up (   self,
  prec 
) [private]
Rounds away from 0.

Definition at line 1710 of file decimal.py.

01710 
01711     def _round_up(self, prec):
01712         """Rounds away from 0."""
01713         return -self._round_down(prec)

Here is the call graph for this function:

def decimal.Decimal.adjusted (   self)
Return the adjusted exponent of self

Definition at line 2834 of file decimal.py.

02834 
02835     def adjusted(self):
02836         """Return the adjusted exponent of self"""
02837         try:
02838             return self._exp + len(self._int) - 1
02839         # If NaN or Infinity, self._exp is string
02840         except TypeError:
02841             return 0

Here is the caller graph for this function:

def decimal.Decimal.as_tuple (   self)
Represents the number as a triple tuple.

To show the internals exactly as they are.

Definition at line 964 of file decimal.py.

00964 
00965     def as_tuple(self):
00966         """Represents the number as a triple tuple.
00967 
00968         To show the internals exactly as they are.
00969         """
00970         return DecimalTuple(self._sign, tuple(map(int, self._int)), self._exp)

Here is the caller graph for this function:

def decimal.Decimal.canonical (   self,
  context = None 
)
Returns the same Decimal object.

As we do not have different encodings for the same number, the
received object already is in its canonical form.

Definition at line 2842 of file decimal.py.

02842 
02843     def canonical(self, context=None):
02844         """Returns the same Decimal object.
02845 
02846         As we do not have different encodings for the same number, the
02847         received object already is in its canonical form.
02848         """
02849         return self

def decimal.Decimal.compare (   self,
  other,
  context = None 
)
Compares one to another.

-1 => a < b
0  => a = b
1  => a > b
NaN => one is NaN
Like __cmp__, but returns Decimal instances.

Definition at line 919 of file decimal.py.

00919 
00920     def compare(self, other, context=None):
00921         """Compares one to another.
00922 
00923         -1 => a < b
00924         0  => a = b
00925         1  => a > b
00926         NaN => one is NaN
00927         Like __cmp__, but returns Decimal instances.
00928         """
00929         other = _convert_other(other, raiseit=True)
00930 
00931         # Compare(NaN, NaN) = NaN
00932         if (self._is_special or other and other._is_special):
00933             ans = self._check_nans(other, context)
00934             if ans:
00935                 return ans
00936 
00937         return Decimal(self._cmp(other))

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.compare_signal (   self,
  other,
  context = None 
)
Compares self to the other operand numerically.

It's pretty much like compare(), but all NaNs signal, with signaling
NaNs taking precedence over quiet NaNs.

Definition at line 2850 of file decimal.py.

02850 
02851     def compare_signal(self, other, context=None):
02852         """Compares self to the other operand numerically.
02853 
02854         It's pretty much like compare(), but all NaNs signal, with signaling
02855         NaNs taking precedence over quiet NaNs.
02856         """
02857         other = _convert_other(other, raiseit = True)
02858         ans = self._compare_check_nans(other, context)
02859         if ans:
02860             return ans
02861         return self.compare(other, context=context)

Here is the call graph for this function:

def decimal.Decimal.compare_total (   self,
  other 
)
Compares self to other using the abstract representations.

This is not like the standard compare, which use their numerical
value. Note that a total ordering is defined for all possible abstract
representations.

Definition at line 2862 of file decimal.py.

02862 
02863     def compare_total(self, other):
02864         """Compares self to other using the abstract representations.
02865 
02866         This is not like the standard compare, which use their numerical
02867         value. Note that a total ordering is defined for all possible abstract
02868         representations.
02869         """
02870         other = _convert_other(other, raiseit=True)
02871 
02872         # if one is negative and the other is positive, it's easy
02873         if self._sign and not other._sign:
02874             return _NegativeOne
02875         if not self._sign and other._sign:
02876             return _One
02877         sign = self._sign
02878 
02879         # let's handle both NaN types
02880         self_nan = self._isnan()
02881         other_nan = other._isnan()
02882         if self_nan or other_nan:
02883             if self_nan == other_nan:
02884                 # compare payloads as though they're integers
02885                 self_key = len(self._int), self._int
02886                 other_key = len(other._int), other._int
02887                 if self_key < other_key:
02888                     if sign:
02889                         return _One
02890                     else:
02891                         return _NegativeOne
02892                 if self_key > other_key:
02893                     if sign:
02894                         return _NegativeOne
02895                     else:
02896                         return _One
02897                 return _Zero
02898 
02899             if sign:
02900                 if self_nan == 1:
02901                     return _NegativeOne
02902                 if other_nan == 1:
02903                     return _One
02904                 if self_nan == 2:
02905                     return _NegativeOne
02906                 if other_nan == 2:
02907                     return _One
02908             else:
02909                 if self_nan == 1:
02910                     return _One
02911                 if other_nan == 1:
02912                     return _NegativeOne
02913                 if self_nan == 2:
02914                     return _One
02915                 if other_nan == 2:
02916                     return _NegativeOne
02917 
02918         if self < other:
02919             return _NegativeOne
02920         if self > other:
02921             return _One
02922 
02923         if self._exp < other._exp:
02924             if sign:
02925                 return _One
02926             else:
02927                 return _NegativeOne
02928         if self._exp > other._exp:
02929             if sign:
02930                 return _NegativeOne
02931             else:
02932                 return _One
02933         return _Zero
02934 

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.compare_total_mag (   self,
  other 
)
Compares self to other using abstract repr., ignoring sign.

Like compare_total, but with operand's sign ignored and assumed to be 0.

Definition at line 2935 of file decimal.py.

02935 
02936     def compare_total_mag(self, other):
02937         """Compares self to other using abstract repr., ignoring sign.
02938 
02939         Like compare_total, but with operand's sign ignored and assumed to be 0.
02940         """
02941         other = _convert_other(other, raiseit=True)
02942 
02943         s = self.copy_abs()
02944         o = other.copy_abs()
02945         return s.compare_total(o)

Here is the call graph for this function:

def decimal.Decimal.conjugate (   self)

Definition at line 1583 of file decimal.py.

01583 
01584     def conjugate(self):
01585         return self

def decimal.Decimal.copy_abs (   self)
Returns a copy with the sign set to 0. 

Definition at line 2946 of file decimal.py.

02946 
02947     def copy_abs(self):
02948         """Returns a copy with the sign set to 0. """
02949         return _dec_from_triple(0, self._int, self._exp, self._is_special)

Here is the call graph for this function:

Here is the caller graph for this function:

Returns a copy with the sign inverted.

Definition at line 2950 of file decimal.py.

02950 
02951     def copy_negate(self):
02952         """Returns a copy with the sign inverted."""
02953         if self._sign:
02954             return _dec_from_triple(0, self._int, self._exp, self._is_special)
02955         else:
02956             return _dec_from_triple(1, self._int, self._exp, self._is_special)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.copy_sign (   self,
  other 
)
Returns self with the sign of other.

Definition at line 2957 of file decimal.py.

02957 
02958     def copy_sign(self, other):
02959         """Returns self with the sign of other."""
02960         other = _convert_other(other, raiseit=True)
02961         return _dec_from_triple(other._sign, self._int,
02962                                 self._exp, self._is_special)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.exp (   self,
  context = None 
)
Returns e ** self.

Definition at line 2963 of file decimal.py.

02963 
02964     def exp(self, context=None):
02965         """Returns e ** self."""
02966 
02967         if context is None:
02968             context = getcontext()
02969 
02970         # exp(NaN) = NaN
02971         ans = self._check_nans(context=context)
02972         if ans:
02973             return ans
02974 
02975         # exp(-Infinity) = 0
02976         if self._isinfinity() == -1:
02977             return _Zero
02978 
02979         # exp(0) = 1
02980         if not self:
02981             return _One
02982 
02983         # exp(Infinity) = Infinity
02984         if self._isinfinity() == 1:
02985             return Decimal(self)
02986 
02987         # the result is now guaranteed to be inexact (the true
02988         # mathematical result is transcendental). There's no need to
02989         # raise Rounded and Inexact here---they'll always be raised as
02990         # a result of the call to _fix.
02991         p = context.prec
02992         adj = self.adjusted()
02993 
02994         # we only need to do any computation for quite a small range
02995         # of adjusted exponents---for example, -29 <= adj <= 10 for
02996         # the default context.  For smaller exponent the result is
02997         # indistinguishable from 1 at the given precision, while for
02998         # larger exponent the result either overflows or underflows.
02999         if self._sign == 0 and adj > len(str((context.Emax+1)*3)):
03000             # overflow
03001             ans = _dec_from_triple(0, '1', context.Emax+1)
03002         elif self._sign == 1 and adj > len(str((-context.Etiny()+1)*3)):
03003             # underflow to 0
03004             ans = _dec_from_triple(0, '1', context.Etiny()-1)
03005         elif self._sign == 0 and adj < -p:
03006             # p+1 digits; final round will raise correct flags
03007             ans = _dec_from_triple(0, '1' + '0'*(p-1) + '1', -p)
03008         elif self._sign == 1 and adj < -p-1:
03009             # p+1 digits; final round will raise correct flags
03010             ans = _dec_from_triple(0, '9'*(p+1), -p-1)
03011         # general case
03012         else:
03013             op = _WorkRep(self)
03014             c, e = op.int, op.exp
03015             if op.sign == 1:
03016                 c = -c
03017 
03018             # compute correctly rounded result: increase precision by
03019             # 3 digits at a time until we get an unambiguously
03020             # roundable result
03021             extra = 3
03022             while True:
03023                 coeff, exp = _dexp(c, e, p+extra)
03024                 if coeff % (5*10**(len(str(coeff))-p-1)):
03025                     break
03026                 extra += 3
03027 
03028             ans = _dec_from_triple(0, str(coeff), exp)
03029 
03030         # at this stage, ans should round correctly with *any*
03031         # rounding mode, not just with ROUND_HALF_EVEN
03032         context = context._shallow_copy()
03033         rounding = context._set_rounding(ROUND_HALF_EVEN)
03034         ans = ans._fix(context)
03035         context.rounding = rounding
03036 
03037         return ans

Here is the call graph for this function:

def decimal.Decimal.fma (   self,
  other,
  third,
  context = None 
)
Fused multiply-add.

Returns self*other+third with no rounding of the intermediate
product self*other.

self and other are multiplied together, with no rounding of
the result.  The third operand is then added to the result,
and a single final rounding is performed.

Definition at line 1862 of file decimal.py.

01862 
01863     def fma(self, other, third, context=None):
01864         """Fused multiply-add.
01865 
01866         Returns self*other+third with no rounding of the intermediate
01867         product self*other.
01868 
01869         self and other are multiplied together, with no rounding of
01870         the result.  The third operand is then added to the result,
01871         and a single final rounding is performed.
01872         """
01873 
01874         other = _convert_other(other, raiseit=True)
01875 
01876         # compute product; raise InvalidOperation if either operand is
01877         # a signaling NaN or if the product is zero times infinity.
01878         if self._is_special or other._is_special:
01879             if context is None:
01880                 context = getcontext()
01881             if self._exp == 'N':
01882                 return context._raise_error(InvalidOperation, 'sNaN', self)
01883             if other._exp == 'N':
01884                 return context._raise_error(InvalidOperation, 'sNaN', other)
01885             if self._exp == 'n':
01886                 product = self
01887             elif other._exp == 'n':
01888                 product = other
01889             elif self._exp == 'F':
01890                 if not other:
01891                     return context._raise_error(InvalidOperation,
01892                                                 'INF * 0 in fma')
01893                 product = _SignedInfinity[self._sign ^ other._sign]
01894             elif other._exp == 'F':
01895                 if not self:
01896                     return context._raise_error(InvalidOperation,
01897                                                 '0 * INF in fma')
01898                 product = _SignedInfinity[self._sign ^ other._sign]
01899         else:
01900             product = _dec_from_triple(self._sign ^ other._sign,
01901                                        str(int(self._int) * int(other._int)),
01902                                        self._exp + other._exp)
01903 
01904         third = _convert_other(third, raiseit=True)
01905         return product.__add__(third, context)

Here is the call graph for this function:

def decimal.Decimal.from_float (   cls,
  f 
)
Converts a float to a decimal number, exactly.

Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
Since 0.1 is not exactly representable in binary floating point, the
value is stored as the nearest representable value which is
0x1.999999999999ap-4.  The exact equivalent of the value in decimal
is 0.1000000000000000055511151231257827021181583404541015625.

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(-float('inf'))
Decimal('-Infinity')
>>> Decimal.from_float(-0.0)
Decimal('-0')

Definition at line 664 of file decimal.py.

00664 
00665     def from_float(cls, f):
00666         """Converts a float to a decimal number, exactly.
00667 
00668         Note that Decimal.from_float(0.1) is not the same as Decimal('0.1').
00669         Since 0.1 is not exactly representable in binary floating point, the
00670         value is stored as the nearest representable value which is
00671         0x1.999999999999ap-4.  The exact equivalent of the value in decimal
00672         is 0.1000000000000000055511151231257827021181583404541015625.
00673 
00674         >>> Decimal.from_float(0.1)
00675         Decimal('0.1000000000000000055511151231257827021181583404541015625')
00676         >>> Decimal.from_float(float('nan'))
00677         Decimal('NaN')
00678         >>> Decimal.from_float(float('inf'))
00679         Decimal('Infinity')
00680         >>> Decimal.from_float(-float('inf'))
00681         Decimal('-Infinity')
00682         >>> Decimal.from_float(-0.0)
00683         Decimal('-0')
00684 
00685         """
00686         if isinstance(f, int):                # handle integer inputs
00687             return cls(f)
00688         if _math.isinf(f) or _math.isnan(f):  # raises TypeError if not a float
00689             return cls(repr(f))
00690         if _math.copysign(1.0, f) == 1.0:
00691             sign = 0
00692         else:
00693             sign = 1
00694         n, d = abs(f).as_integer_ratio()
00695         k = d.bit_length() - 1
00696         result = _dec_from_triple(sign, str(n*5**k), -k)
00697         if cls is Decimal:
00698             return result
00699         else:
            return cls(result)

Here is the call graph for this function:

def decimal.Decimal.imag (   self)

Definition at line 1579 of file decimal.py.

01579 
01580     def imag(self):
        return Decimal(0)
Return True if self is canonical; otherwise return False.

Currently, the encoding of a Decimal instance is always
canonical, so this method returns True for any Decimal.

Definition at line 3038 of file decimal.py.

03038 
03039     def is_canonical(self):
03040         """Return True if self is canonical; otherwise return False.
03041 
03042         Currently, the encoding of a Decimal instance is always
03043         canonical, so this method returns True for any Decimal.
03044         """
03045         return True

def decimal.Decimal.is_finite (   self)
Return True if self is finite; otherwise return False.

A Decimal instance is considered finite if it is neither
infinite nor a NaN.

Definition at line 3046 of file decimal.py.

03046 
03047     def is_finite(self):
03048         """Return True if self is finite; otherwise return False.
03049 
03050         A Decimal instance is considered finite if it is neither
03051         infinite nor a NaN.
03052         """
03053         return not self._is_special

Return True if self is infinite; otherwise return False.

Definition at line 3054 of file decimal.py.

03054 
03055     def is_infinite(self):
03056         """Return True if self is infinite; otherwise return False."""
03057         return self._exp == 'F'

Here is the caller graph for this function:

def decimal.Decimal.is_nan (   self)
Return True if self is a qNaN or sNaN; otherwise return False.

Definition at line 3058 of file decimal.py.

03058 
03059     def is_nan(self):
03060         """Return True if self is a qNaN or sNaN; otherwise return False."""
03061         return self._exp in ('n', 'N')

Here is the caller graph for this function:

def decimal.Decimal.is_normal (   self,
  context = None 
)
Return True if self is a normal number; otherwise return False.

Definition at line 3062 of file decimal.py.

03062 
03063     def is_normal(self, context=None):
03064         """Return True if self is a normal number; otherwise return False."""
03065         if self._is_special or not self:
03066             return False
03067         if context is None:
03068             context = getcontext()
03069         return context.Emin <= self.adjusted()

Here is the call graph for this function:

def decimal.Decimal.is_qnan (   self)
Return True if self is a quiet NaN; otherwise return False.

Definition at line 3070 of file decimal.py.

03070 
03071     def is_qnan(self):
03072         """Return True if self is a quiet NaN; otherwise return False."""
03073         return self._exp == 'n'

Here is the caller graph for this function:

def decimal.Decimal.is_signed (   self)
Return True if self is negative; otherwise return False.

Definition at line 3074 of file decimal.py.

03074 
03075     def is_signed(self):
03076         """Return True if self is negative; otherwise return False."""
03077         return self._sign == 1

def decimal.Decimal.is_snan (   self)
Return True if self is a signaling NaN; otherwise return False.

Definition at line 3078 of file decimal.py.

03078 
03079     def is_snan(self):
03080         """Return True if self is a signaling NaN; otherwise return False."""
03081         return self._exp == 'N'

Here is the caller graph for this function:

def decimal.Decimal.is_subnormal (   self,
  context = None 
)
Return True if self is subnormal; otherwise return False.

Definition at line 3082 of file decimal.py.

03082 
03083     def is_subnormal(self, context=None):
03084         """Return True if self is subnormal; otherwise return False."""
03085         if self._is_special or not self:
03086             return False
03087         if context is None:
03088             context = getcontext()
03089         return self.adjusted() < context.Emin

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.is_zero (   self)
Return True if self is a zero; otherwise return False.

Definition at line 3090 of file decimal.py.

03090 
03091     def is_zero(self):
03092         """Return True if self is a zero; otherwise return False."""
03093         return not self._is_special and self._int == '0'

Here is the caller graph for this function:

def decimal.Decimal.ln (   self,
  context = None 
)
Returns the natural (base e) logarithm of self.

Definition at line 3119 of file decimal.py.

03119 
03120     def ln(self, context=None):
03121         """Returns the natural (base e) logarithm of self."""
03122 
03123         if context is None:
03124             context = getcontext()
03125 
03126         # ln(NaN) = NaN
03127         ans = self._check_nans(context=context)
03128         if ans:
03129             return ans
03130 
03131         # ln(0.0) == -Infinity
03132         if not self:
03133             return _NegativeInfinity
03134 
03135         # ln(Infinity) = Infinity
03136         if self._isinfinity() == 1:
03137             return _Infinity
03138 
03139         # ln(1.0) == 0.0
03140         if self == _One:
03141             return _Zero
03142 
03143         # ln(negative) raises InvalidOperation
03144         if self._sign == 1:
03145             return context._raise_error(InvalidOperation,
03146                                         'ln of a negative value')
03147 
03148         # result is irrational, so necessarily inexact
03149         op = _WorkRep(self)
03150         c, e = op.int, op.exp
03151         p = context.prec
03152 
03153         # correctly rounded result: repeatedly increase precision by 3
03154         # until we get an unambiguously roundable result
03155         places = p - self._ln_exp_bound() + 2 # at least p+3 places
03156         while True:
03157             coeff = _dlog(c, e, places)
03158             # assert len(str(abs(coeff)))-p >= 1
03159             if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
03160                 break
03161             places += 3
03162         ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
03163 
03164         context = context._shallow_copy()
03165         rounding = context._set_rounding(ROUND_HALF_EVEN)
03166         ans = ans._fix(context)
03167         context.rounding = rounding
03168         return ans

Here is the call graph for this function:

def decimal.Decimal.log10 (   self,
  context = None 
)
Returns the base 10 logarithm of self.

Definition at line 3199 of file decimal.py.

03199 
03200     def log10(self, context=None):
03201         """Returns the base 10 logarithm of self."""
03202 
03203         if context is None:
03204             context = getcontext()
03205 
03206         # log10(NaN) = NaN
03207         ans = self._check_nans(context=context)
03208         if ans:
03209             return ans
03210 
03211         # log10(0.0) == -Infinity
03212         if not self:
03213             return _NegativeInfinity
03214 
03215         # log10(Infinity) = Infinity
03216         if self._isinfinity() == 1:
03217             return _Infinity
03218 
03219         # log10(negative or -Infinity) raises InvalidOperation
03220         if self._sign == 1:
03221             return context._raise_error(InvalidOperation,
03222                                         'log10 of a negative value')
03223 
03224         # log10(10**n) = n
03225         if self._int[0] == '1' and self._int[1:] == '0'*(len(self._int) - 1):
03226             # answer may need rounding
03227             ans = Decimal(self._exp + len(self._int) - 1)
03228         else:
03229             # result is irrational, so necessarily inexact
03230             op = _WorkRep(self)
03231             c, e = op.int, op.exp
03232             p = context.prec
03233 
03234             # correctly rounded result: repeatedly increase precision
03235             # until result is unambiguously roundable
03236             places = p-self._log10_exp_bound()+2
03237             while True:
03238                 coeff = _dlog10(c, e, places)
03239                 # assert len(str(abs(coeff)))-p >= 1
03240                 if coeff % (5*10**(len(str(abs(coeff)))-p-1)):
03241                     break
03242                 places += 3
03243             ans = _dec_from_triple(int(coeff<0), str(abs(coeff)), -places)
03244 
03245         context = context._shallow_copy()
03246         rounding = context._set_rounding(ROUND_HALF_EVEN)
03247         ans = ans._fix(context)
03248         context.rounding = rounding
03249         return ans

Here is the call graph for this function:

def decimal.Decimal.logb (   self,
  context = None 
)
Returns the exponent of the magnitude of self's MSD.

The result is the integer which is the exponent of the magnitude
of the most significant digit of self (as though it were truncated
to a single digit while maintaining the value of that digit and
without limiting the resulting exponent).

Definition at line 3250 of file decimal.py.

03250 
03251     def logb(self, context=None):
03252         """ Returns the exponent of the magnitude of self's MSD.
03253 
03254         The result is the integer which is the exponent of the magnitude
03255         of the most significant digit of self (as though it were truncated
03256         to a single digit while maintaining the value of that digit and
03257         without limiting the resulting exponent).
03258         """
03259         # logb(NaN) = NaN
03260         ans = self._check_nans(context=context)
03261         if ans:
03262             return ans
03263 
03264         if context is None:
03265             context = getcontext()
03266 
03267         # logb(+/-Inf) = +Inf
03268         if self._isinfinity():
03269             return _Infinity
03270 
03271         # logb(0) = -Inf, DivisionByZero
03272         if not self:
03273             return context._raise_error(DivisionByZero, 'logb(0)', 1)
03274 
03275         # otherwise, simply return the adjusted exponent of self, as a
03276         # Decimal.  Note that no attempt is made to fit the result
03277         # into the current context.
03278         ans = Decimal(self.adjusted())
03279         return ans._fix(context)

Here is the call graph for this function:

def decimal.Decimal.logical_and (   self,
  other,
  context = None 
)
Applies an 'and' operation between self and other's digits.

Definition at line 3307 of file decimal.py.

03307 
03308     def logical_and(self, other, context=None):
03309         """Applies an 'and' operation between self and other's digits."""
03310         if context is None:
03311             context = getcontext()
03312 
03313         other = _convert_other(other, raiseit=True)
03314 
03315         if not self._islogical() or not other._islogical():
03316             return context._raise_error(InvalidOperation)
03317 
03318         # fill to context.prec
03319         (opa, opb) = self._fill_logical(context, self._int, other._int)
03320 
03321         # make the operation, and clean starting zeroes
03322         result = "".join([str(int(a)&int(b)) for a,b in zip(opa,opb)])
03323         return _dec_from_triple(0, result.lstrip('0') or '0', 0)

Here is the call graph for this function:

def decimal.Decimal.logical_invert (   self,
  context = None 
)
Invert all its digits.

Definition at line 3324 of file decimal.py.

03324 
03325     def logical_invert(self, context=None):
03326         """Invert all its digits."""
03327         if context is None:
03328             context = getcontext()
03329         return self.logical_xor(_dec_from_triple(0,'1'*context.prec,0),
03330                                 context)

Here is the call graph for this function:

def decimal.Decimal.logical_or (   self,
  other,
  context = None 
)
Applies an 'or' operation between self and other's digits.

Definition at line 3331 of file decimal.py.

03331 
03332     def logical_or(self, other, context=None):
03333         """Applies an 'or' operation between self and other's digits."""
03334         if context is None:
03335             context = getcontext()
03336 
03337         other = _convert_other(other, raiseit=True)
03338 
03339         if not self._islogical() or not other._islogical():
03340             return context._raise_error(InvalidOperation)
03341 
03342         # fill to context.prec
03343         (opa, opb) = self._fill_logical(context, self._int, other._int)
03344 
03345         # make the operation, and clean starting zeroes
03346         result = "".join([str(int(a)|int(b)) for a,b in zip(opa,opb)])
03347         return _dec_from_triple(0, result.lstrip('0') or '0', 0)

Here is the call graph for this function:

def decimal.Decimal.logical_xor (   self,
  other,
  context = None 
)
Applies an 'xor' operation between self and other's digits.

Definition at line 3348 of file decimal.py.

03348 
03349     def logical_xor(self, other, context=None):
03350         """Applies an 'xor' operation between self and other's digits."""
03351         if context is None:
03352             context = getcontext()
03353 
03354         other = _convert_other(other, raiseit=True)
03355 
03356         if not self._islogical() or not other._islogical():
03357             return context._raise_error(InvalidOperation)
03358 
03359         # fill to context.prec
03360         (opa, opb) = self._fill_logical(context, self._int, other._int)
03361 
03362         # make the operation, and clean starting zeroes
03363         result = "".join([str(int(a)^int(b)) for a,b in zip(opa,opb)])
03364         return _dec_from_triple(0, result.lstrip('0') or '0', 0)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.max (   self,
  other,
  context = None 
)
Returns the larger value.

Like max(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN).  Also rounds.

Definition at line 2743 of file decimal.py.

02743 
02744     def max(self, other, context=None):
02745         """Returns the larger value.
02746 
02747         Like max(self, other) except if one is not a number, returns
02748         NaN (and signals if one is sNaN).  Also rounds.
02749         """
02750         other = _convert_other(other, raiseit=True)
02751 
02752         if context is None:
02753             context = getcontext()
02754 
02755         if self._is_special or other._is_special:
02756             # If one operand is a quiet NaN and the other is number, then the
02757             # number is always returned
02758             sn = self._isnan()
02759             on = other._isnan()
02760             if sn or on:
02761                 if on == 1 and sn == 0:
02762                     return self._fix(context)
02763                 if sn == 1 and on == 0:
02764                     return other._fix(context)
02765                 return self._check_nans(other, context)
02766 
02767         c = self._cmp(other)
02768         if c == 0:
02769             # If both operands are finite and equal in numerical value
02770             # then an ordering is applied:
02771             #
02772             # If the signs differ then max returns the operand with the
02773             # positive sign and min returns the operand with the negative sign
02774             #
02775             # If the signs are the same then the exponent is used to select
02776             # the result.  This is exactly the ordering used in compare_total.
02777             c = self.compare_total(other)
02778 
02779         if c == -1:
02780             ans = other
02781         else:
02782             ans = self
02783 
02784         return ans._fix(context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.max_mag (   self,
  other,
  context = None 
)
Compares the values numerically with their sign ignored.

Definition at line 3365 of file decimal.py.

03365 
03366     def max_mag(self, other, context=None):
03367         """Compares the values numerically with their sign ignored."""
03368         other = _convert_other(other, raiseit=True)
03369 
03370         if context is None:
03371             context = getcontext()
03372 
03373         if self._is_special or other._is_special:
03374             # If one operand is a quiet NaN and the other is number, then the
03375             # number is always returned
03376             sn = self._isnan()
03377             on = other._isnan()
03378             if sn or on:
03379                 if on == 1 and sn == 0:
03380                     return self._fix(context)
03381                 if sn == 1 and on == 0:
03382                     return other._fix(context)
03383                 return self._check_nans(other, context)
03384 
03385         c = self.copy_abs()._cmp(other.copy_abs())
03386         if c == 0:
03387             c = self.compare_total(other)
03388 
03389         if c == -1:
03390             ans = other
03391         else:
03392             ans = self
03393 
03394         return ans._fix(context)

Here is the call graph for this function:

def decimal.Decimal.min (   self,
  other,
  context = None 
)
Returns the smaller value.

Like min(self, other) except if one is not a number, returns
NaN (and signals if one is sNaN).  Also rounds.

Definition at line 2785 of file decimal.py.

02785 
02786     def min(self, other, context=None):
02787         """Returns the smaller value.
02788 
02789         Like min(self, other) except if one is not a number, returns
02790         NaN (and signals if one is sNaN).  Also rounds.
02791         """
02792         other = _convert_other(other, raiseit=True)
02793 
02794         if context is None:
02795             context = getcontext()
02796 
02797         if self._is_special or other._is_special:
02798             # If one operand is a quiet NaN and the other is number, then the
02799             # number is always returned
02800             sn = self._isnan()
02801             on = other._isnan()
02802             if sn or on:
02803                 if on == 1 and sn == 0:
02804                     return self._fix(context)
02805                 if sn == 1 and on == 0:
02806                     return other._fix(context)
02807                 return self._check_nans(other, context)
02808 
02809         c = self._cmp(other)
02810         if c == 0:
02811             c = self.compare_total(other)
02812 
02813         if c == -1:
02814             ans = self
02815         else:
02816             ans = other
02817 
02818         return ans._fix(context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.min_mag (   self,
  other,
  context = None 
)
Compares the values numerically with their sign ignored.

Definition at line 3395 of file decimal.py.

03395 
03396     def min_mag(self, other, context=None):
03397         """Compares the values numerically with their sign ignored."""
03398         other = _convert_other(other, raiseit=True)
03399 
03400         if context is None:
03401             context = getcontext()
03402 
03403         if self._is_special or other._is_special:
03404             # If one operand is a quiet NaN and the other is number, then the
03405             # number is always returned
03406             sn = self._isnan()
03407             on = other._isnan()
03408             if sn or on:
03409                 if on == 1 and sn == 0:
03410                     return self._fix(context)
03411                 if sn == 1 and on == 0:
03412                     return other._fix(context)
03413                 return self._check_nans(other, context)
03414 
03415         c = self.copy_abs()._cmp(other.copy_abs())
03416         if c == 0:
03417             c = self.compare_total(other)
03418 
03419         if c == -1:
03420             ans = self
03421         else:
03422             ans = other
03423 
03424         return ans._fix(context)

Here is the call graph for this function:

def decimal.Decimal.next_minus (   self,
  context = None 
)
Returns the largest representable number smaller than itself.

Definition at line 3425 of file decimal.py.

03425 
03426     def next_minus(self, context=None):
03427         """Returns the largest representable number smaller than itself."""
03428         if context is None:
03429             context = getcontext()
03430 
03431         ans = self._check_nans(context=context)
03432         if ans:
03433             return ans
03434 
03435         if self._isinfinity() == -1:
03436             return _NegativeInfinity
03437         if self._isinfinity() == 1:
03438             return _dec_from_triple(0, '9'*context.prec, context.Etop())
03439 
03440         context = context.copy()
03441         context._set_rounding(ROUND_FLOOR)
03442         context._ignore_all_flags()
03443         new_self = self._fix(context)
03444         if new_self != self:
03445             return new_self
03446         return self.__sub__(_dec_from_triple(0, '1', context.Etiny()-1),
03447                             context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.next_plus (   self,
  context = None 
)
Returns the smallest representable number larger than itself.

Definition at line 3448 of file decimal.py.

03448 
03449     def next_plus(self, context=None):
03450         """Returns the smallest representable number larger than itself."""
03451         if context is None:
03452             context = getcontext()
03453 
03454         ans = self._check_nans(context=context)
03455         if ans:
03456             return ans
03457 
03458         if self._isinfinity() == 1:
03459             return _Infinity
03460         if self._isinfinity() == -1:
03461             return _dec_from_triple(1, '9'*context.prec, context.Etop())
03462 
03463         context = context.copy()
03464         context._set_rounding(ROUND_CEILING)
03465         context._ignore_all_flags()
03466         new_self = self._fix(context)
03467         if new_self != self:
03468             return new_self
03469         return self.__add__(_dec_from_triple(0, '1', context.Etiny()-1),
03470                             context)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.next_toward (   self,
  other,
  context = None 
)
Returns the number closest to self, in the direction towards other.

The result is the closest representable number to self
(excluding self) that is in the direction towards other,
unless both have the same value.  If the two operands are
numerically equal, then the result is a copy of self with the
sign set to be the same as the sign of other.

Definition at line 3471 of file decimal.py.

03471 
03472     def next_toward(self, other, context=None):
03473         """Returns the number closest to self, in the direction towards other.
03474 
03475         The result is the closest representable number to self
03476         (excluding self) that is in the direction towards other,
03477         unless both have the same value.  If the two operands are
03478         numerically equal, then the result is a copy of self with the
03479         sign set to be the same as the sign of other.
03480         """
03481         other = _convert_other(other, raiseit=True)
03482 
03483         if context is None:
03484             context = getcontext()
03485 
03486         ans = self._check_nans(other, context)
03487         if ans:
03488             return ans
03489 
03490         comparison = self._cmp(other)
03491         if comparison == 0:
03492             return self.copy_sign(other)
03493 
03494         if comparison == -1:
03495             ans = self.next_plus(context)
03496         else: # comparison == 1
03497             ans = self.next_minus(context)
03498 
03499         # decide which flags to raise using value of ans
03500         if ans._isinfinity():
03501             context._raise_error(Overflow,
03502                                  'Infinite result from next_toward',
03503                                  ans._sign)
03504             context._raise_error(Inexact)
03505             context._raise_error(Rounded)
03506         elif ans.adjusted() < context.Emin:
03507             context._raise_error(Underflow)
03508             context._raise_error(Subnormal)
03509             context._raise_error(Inexact)
03510             context._raise_error(Rounded)
03511             # if precision == 1 then we don't raise Clamped for a
03512             # result 0E-Etiny.
03513             if not ans:
03514                 context._raise_error(Clamped)
03515 
03516         return ans

Here is the call graph for this function:

def decimal.Decimal.normalize (   self,
  context = None 
)
Normalize- strip trailing 0s, change anything equal to 0 to 0e0

Definition at line 2428 of file decimal.py.

02428 
02429     def normalize(self, context=None):
02430         """Normalize- strip trailing 0s, change anything equal to 0 to 0e0"""
02431 
02432         if context is None:
02433             context = getcontext()
02434 
02435         if self._is_special:
02436             ans = self._check_nans(context=context)
02437             if ans:
02438                 return ans
02439 
02440         dup = self._fix(context)
02441         if dup._isinfinity():
02442             return dup
02443 
02444         if not dup:
02445             return _dec_from_triple(dup._sign, '0', 0)
02446         exp_max = [context.Emax, context.Etop()][context.clamp]
02447         end = len(dup._int)
02448         exp = dup._exp
02449         while dup._int[end-1] == '0' and exp < exp_max:
02450             exp += 1
02451             end -= 1
02452         return _dec_from_triple(dup._sign, dup._int[:end], exp)

Here is the call graph for this function:

def decimal.Decimal.number_class (   self,
  context = None 
)
Returns an indication of the class of self.

The class is one of the following strings:
  sNaN
  NaN
  -Infinity
  -Normal
  -Subnormal
  -Zero
  +Zero
  +Subnormal
  +Normal
  +Infinity

Definition at line 3517 of file decimal.py.

03517 
03518     def number_class(self, context=None):
03519         """Returns an indication of the class of self.
03520 
03521         The class is one of the following strings:
03522           sNaN
03523           NaN
03524           -Infinity
03525           -Normal
03526           -Subnormal
03527           -Zero
03528           +Zero
03529           +Subnormal
03530           +Normal
03531           +Infinity
03532         """
03533         if self.is_snan():
03534             return "sNaN"
03535         if self.is_qnan():
03536             return "NaN"
03537         inf = self._isinfinity()
03538         if inf == 1:
03539             return "+Infinity"
03540         if inf == -1:
03541             return "-Infinity"
03542         if self.is_zero():
03543             if self._sign:
03544                 return "-Zero"
03545             else:
03546                 return "+Zero"
03547         if context is None:
03548             context = getcontext()
03549         if self.is_subnormal(context=context):
03550             if self._sign:
03551                 return "-Subnormal"
03552             else:
03553                 return "+Subnormal"
03554         # just a normal, regular, boring number, :)
03555         if self._sign:
03556             return "-Normal"
03557         else:
03558             return "+Normal"

Here is the call graph for this function:

def decimal.Decimal.quantize (   self,
  exp,
  rounding = None,
  context = None,
  watchexp = True 
)
Quantize self so its exponent is the same as that of exp.

Similar to self._rescale(exp._exp) but with error checking.

Definition at line 2453 of file decimal.py.

02453 
02454     def quantize(self, exp, rounding=None, context=None, watchexp=True):
02455         """Quantize self so its exponent is the same as that of exp.
02456 
02457         Similar to self._rescale(exp._exp) but with error checking.
02458         """
02459         exp = _convert_other(exp, raiseit=True)
02460 
02461         if context is None:
02462             context = getcontext()
02463         if rounding is None:
02464             rounding = context.rounding
02465 
02466         if self._is_special or exp._is_special:
02467             ans = self._check_nans(exp, context)
02468             if ans:
02469                 return ans
02470 
02471             if exp._isinfinity() or self._isinfinity():
02472                 if exp._isinfinity() and self._isinfinity():
02473                     return Decimal(self)  # if both are inf, it is OK
02474                 return context._raise_error(InvalidOperation,
02475                                         'quantize with one INF')
02476 
02477         # if we're not watching exponents, do a simple rescale
02478         if not watchexp:
02479             ans = self._rescale(exp._exp, rounding)
02480             # raise Inexact and Rounded where appropriate
02481             if ans._exp > self._exp:
02482                 context._raise_error(Rounded)
02483                 if ans != self:
02484                     context._raise_error(Inexact)
02485             return ans
02486 
02487         # exp._exp should be between Etiny and Emax
02488         if not (context.Etiny() <= exp._exp <= context.Emax):
02489             return context._raise_error(InvalidOperation,
02490                    'target exponent out of bounds in quantize')
02491 
02492         if not self:
02493             ans = _dec_from_triple(self._sign, '0', exp._exp)
02494             return ans._fix(context)
02495 
02496         self_adjusted = self.adjusted()
02497         if self_adjusted > context.Emax:
02498             return context._raise_error(InvalidOperation,
02499                                         'exponent of quantize result too large for current context')
02500         if self_adjusted - exp._exp + 1 > context.prec:
02501             return context._raise_error(InvalidOperation,
02502                                         'quantize result has too many digits for current context')
02503 
02504         ans = self._rescale(exp._exp, rounding)
02505         if ans.adjusted() > context.Emax:
02506             return context._raise_error(InvalidOperation,
02507                                         'exponent of quantize result too large for current context')
02508         if len(ans._int) > context.prec:
02509             return context._raise_error(InvalidOperation,
02510                                         'quantize result has too many digits for current context')
02511 
02512         # raise appropriate flags
02513         if ans and ans.adjusted() < context.Emin:
02514             context._raise_error(Subnormal)
02515         if ans._exp > self._exp:
02516             if ans != self:
02517                 context._raise_error(Inexact)
02518             context._raise_error(Rounded)
02519 
02520         # call to fix takes care of any necessary folddown, and
02521         # signals Clamped if necessary
02522         ans = ans._fix(context)
02523         return ans

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.radix (   self)
Just returns 10, as this is Decimal, :)

Definition at line 3559 of file decimal.py.

03559 
03560     def radix(self):
03561         """Just returns 10, as this is Decimal, :)"""
03562         return Decimal(10)

def decimal.Decimal.real (   self)

Definition at line 1575 of file decimal.py.

01575 
01576     def real(self):
        return self
def decimal.Decimal.remainder_near (   self,
  other,
  context = None 
)
Remainder nearest to 0-  abs(remainder-near) <= other/2

Definition at line 1446 of file decimal.py.

01446 
01447     def remainder_near(self, other, context=None):
01448         """
01449         Remainder nearest to 0-  abs(remainder-near) <= other/2
01450         """
01451         if context is None:
01452             context = getcontext()
01453 
01454         other = _convert_other(other, raiseit=True)
01455 
01456         ans = self._check_nans(other, context)
01457         if ans:
01458             return ans
01459 
01460         # self == +/-infinity -> InvalidOperation
01461         if self._isinfinity():
01462             return context._raise_error(InvalidOperation,
01463                                         'remainder_near(infinity, x)')
01464 
01465         # other == 0 -> either InvalidOperation or DivisionUndefined
01466         if not other:
01467             if self:
01468                 return context._raise_error(InvalidOperation,
01469                                             'remainder_near(x, 0)')
01470             else:
01471                 return context._raise_error(DivisionUndefined,
01472                                             'remainder_near(0, 0)')
01473 
01474         # other = +/-infinity -> remainder = self
01475         if other._isinfinity():
01476             ans = Decimal(self)
01477             return ans._fix(context)
01478 
01479         # self = 0 -> remainder = self, with ideal exponent
01480         ideal_exponent = min(self._exp, other._exp)
01481         if not self:
01482             ans = _dec_from_triple(self._sign, '0', ideal_exponent)
01483             return ans._fix(context)
01484 
01485         # catch most cases of large or small quotient
01486         expdiff = self.adjusted() - other.adjusted()
01487         if expdiff >= context.prec + 1:
01488             # expdiff >= prec+1 => abs(self/other) > 10**prec
01489             return context._raise_error(DivisionImpossible)
01490         if expdiff <= -2:
01491             # expdiff <= -2 => abs(self/other) < 0.1
01492             ans = self._rescale(ideal_exponent, context.rounding)
01493             return ans._fix(context)
01494 
01495         # adjust both arguments to have the same exponent, then divide
01496         op1 = _WorkRep(self)
01497         op2 = _WorkRep(other)
01498         if op1.exp >= op2.exp:
01499             op1.int *= 10**(op1.exp - op2.exp)
01500         else:
01501             op2.int *= 10**(op2.exp - op1.exp)
01502         q, r = divmod(op1.int, op2.int)
01503         # remainder is r*10**ideal_exponent; other is +/-op2.int *
01504         # 10**ideal_exponent.   Apply correction to ensure that
01505         # abs(remainder) <= abs(other)/2
01506         if 2*r + (q&1) > op2.int:
01507             r -= op2.int
01508             q += 1
01509 
01510         if q >= 10**context.prec:
01511             return context._raise_error(DivisionImpossible)
01512 
01513         # result has same sign as self unless r is negative
01514         sign = self._sign
01515         if r < 0:
01516             sign = 1-sign
01517             r = -r
01518 
01519         ans = _dec_from_triple(sign, str(r), ideal_exponent)
01520         return ans._fix(context)

Here is the call graph for this function:

def decimal.Decimal.rotate (   self,
  other,
  context = None 
)
Returns a rotated copy of self, value-of-other times.

Definition at line 3563 of file decimal.py.

03563 
03564     def rotate(self, other, context=None):
03565         """Returns a rotated copy of self, value-of-other times."""
03566         if context is None:
03567             context = getcontext()
03568 
03569         other = _convert_other(other, raiseit=True)
03570 
03571         ans = self._check_nans(other, context)
03572         if ans:
03573             return ans
03574 
03575         if other._exp != 0:
03576             return context._raise_error(InvalidOperation)
03577         if not (-context.prec <= int(other) <= context.prec):
03578             return context._raise_error(InvalidOperation)
03579 
03580         if self._isinfinity():
03581             return Decimal(self)
03582 
03583         # get values, pad if necessary
03584         torot = int(other)
03585         rotdig = self._int
03586         topad = context.prec - len(rotdig)
03587         if topad > 0:
03588             rotdig = '0'*topad + rotdig
03589         elif topad < 0:
03590             rotdig = rotdig[-topad:]
03591 
03592         # let's rotate!
03593         rotated = rotdig[torot:] + rotdig[:torot]
03594         return _dec_from_triple(self._sign,
03595                                 rotated.lstrip('0') or '0', self._exp)

Here is the call graph for this function:

def decimal.Decimal.same_quantum (   self,
  other 
)
Return True if self and other have the same exponent; otherwise
return False.

If either operand is a special value, the following rules are used:
   * return True if both operands are infinities
   * return True if both operands are NaNs
   * otherwise, return False.

Definition at line 2524 of file decimal.py.

02524 
02525     def same_quantum(self, other):
02526         """Return True if self and other have the same exponent; otherwise
02527         return False.
02528 
02529         If either operand is a special value, the following rules are used:
02530            * return True if both operands are infinities
02531            * return True if both operands are NaNs
02532            * otherwise, return False.
02533         """
02534         other = _convert_other(other, raiseit=True)
02535         if self._is_special or other._is_special:
02536             return (self.is_nan() and other.is_nan() or
02537                     self.is_infinite() and other.is_infinite())
02538         return self._exp == other._exp

Here is the call graph for this function:

def decimal.Decimal.scaleb (   self,
  other,
  context = None 
)
Returns self operand after adding the second value to its exp.

Definition at line 3596 of file decimal.py.

03596 
03597     def scaleb(self, other, context=None):
03598         """Returns self operand after adding the second value to its exp."""
03599         if context is None:
03600             context = getcontext()
03601 
03602         other = _convert_other(other, raiseit=True)
03603 
03604         ans = self._check_nans(other, context)
03605         if ans:
03606             return ans
03607 
03608         if other._exp != 0:
03609             return context._raise_error(InvalidOperation)
03610         liminf = -2 * (context.Emax + context.prec)
03611         limsup =  2 * (context.Emax + context.prec)
03612         if not (liminf <= int(other) <= limsup):
03613             return context._raise_error(InvalidOperation)
03614 
03615         if self._isinfinity():
03616             return Decimal(self)
03617 
03618         d = _dec_from_triple(self._sign, self._int, self._exp + int(other))
03619         d = d._fix(context)
03620         return d

Here is the call graph for this function:

def decimal.Decimal.shift (   self,
  other,
  context = None 
)
Returns a shifted copy of self, value-of-other times.

Definition at line 3621 of file decimal.py.

03621 
03622     def shift(self, other, context=None):
03623         """Returns a shifted copy of self, value-of-other times."""
03624         if context is None:
03625             context = getcontext()
03626 
03627         other = _convert_other(other, raiseit=True)
03628 
03629         ans = self._check_nans(other, context)
03630         if ans:
03631             return ans
03632 
03633         if other._exp != 0:
03634             return context._raise_error(InvalidOperation)
03635         if not (-context.prec <= int(other) <= context.prec):
03636             return context._raise_error(InvalidOperation)
03637 
03638         if self._isinfinity():
03639             return Decimal(self)
03640 
03641         # get values, pad if necessary
03642         torot = int(other)
03643         rotdig = self._int
03644         topad = context.prec - len(rotdig)
03645         if topad > 0:
03646             rotdig = '0'*topad + rotdig
03647         elif topad < 0:
03648             rotdig = rotdig[-topad:]
03649 
03650         # let's shift!
03651         if torot < 0:
03652             shifted = rotdig[:torot]
03653         else:
03654             shifted = rotdig + '0'*torot
03655             shifted = shifted[-context.prec:]
03656 
03657         return _dec_from_triple(self._sign,
03658                                     shifted.lstrip('0') or '0', self._exp)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.Decimal.sqrt (   self,
  context = None 
)
Return the square root of self.

Definition at line 2644 of file decimal.py.

02644 
02645     def sqrt(self, context=None):
02646         """Return the square root of self."""
02647         if context is None:
02648             context = getcontext()
02649 
02650         if self._is_special:
02651             ans = self._check_nans(context=context)
02652             if ans:
02653                 return ans
02654 
02655             if self._isinfinity() and self._sign == 0:
02656                 return Decimal(self)
02657 
02658         if not self:
02659             # exponent = self._exp // 2.  sqrt(-0) = -0
02660             ans = _dec_from_triple(self._sign, '0', self._exp // 2)
02661             return ans._fix(context)
02662 
02663         if self._sign == 1:
02664             return context._raise_error(InvalidOperation, 'sqrt(-x), x > 0')
02665 
02666         # At this point self represents a positive number.  Let p be
02667         # the desired precision and express self in the form c*100**e
02668         # with c a positive real number and e an integer, c and e
02669         # being chosen so that 100**(p-1) <= c < 100**p.  Then the
02670         # (exact) square root of self is sqrt(c)*10**e, and 10**(p-1)
02671         # <= sqrt(c) < 10**p, so the closest representable Decimal at
02672         # precision p is n*10**e where n = round_half_even(sqrt(c)),
02673         # the closest integer to sqrt(c) with the even integer chosen
02674         # in the case of a tie.
02675         #
02676         # To ensure correct rounding in all cases, we use the
02677         # following trick: we compute the square root to an extra
02678         # place (precision p+1 instead of precision p), rounding down.
02679         # Then, if the result is inexact and its last digit is 0 or 5,
02680         # we increase the last digit to 1 or 6 respectively; if it's
02681         # exact we leave the last digit alone.  Now the final round to
02682         # p places (or fewer in the case of underflow) will round
02683         # correctly and raise the appropriate flags.
02684 
02685         # use an extra digit of precision
02686         prec = context.prec+1
02687 
02688         # write argument in the form c*100**e where e = self._exp//2
02689         # is the 'ideal' exponent, to be used if the square root is
02690         # exactly representable.  l is the number of 'digits' of c in
02691         # base 100, so that 100**(l-1) <= c < 100**l.
02692         op = _WorkRep(self)
02693         e = op.exp >> 1
02694         if op.exp & 1:
02695             c = op.int * 10
02696             l = (len(self._int) >> 1) + 1
02697         else:
02698             c = op.int
02699             l = len(self._int)+1 >> 1
02700 
02701         # rescale so that c has exactly prec base 100 'digits'
02702         shift = prec-l
02703         if shift >= 0:
02704             c *= 100**shift
02705             exact = True
02706         else:
02707             c, remainder = divmod(c, 100**-shift)
02708             exact = not remainder
02709         e -= shift
02710 
02711         # find n = floor(sqrt(c)) using Newton's method
02712         n = 10**prec
02713         while True:
02714             q = c//n
02715             if n <= q:
02716                 break
02717             else:
02718                 n = n + q >> 1
02719         exact = exact and n*n == c
02720 
02721         if exact:
02722             # result is exact; rescale to use ideal exponent e
02723             if shift >= 0:
02724                 # assert n % 10**shift == 0
02725                 n //= 10**shift
02726             else:
02727                 n *= 10**-shift
02728             e += shift
02729         else:
02730             # result is not exact; fix last digit as described above
02731             if n % 5 == 0:
02732                 n += 1
02733 
02734         ans = _dec_from_triple(0, str(n), e)
02735 
02736         # round, and fit to current context
02737         context = context._shallow_copy()
02738         rounding = context._set_rounding(ROUND_HALF_EVEN)
02739         ans = ans._fix(context)
02740         context.rounding = rounding
02741 
02742         return ans

Here is the call graph for this function:

def decimal.Decimal.to_eng_string (   self,
  context = None 
)
Convert to engineering-type string.

Engineering notation has an exponent which is a multiple of 3, so there
are up to 3 digits left of the decimal place.

Same rules for when in exponential and when as a value as in __str__.

Definition at line 1028 of file decimal.py.

01028 
01029     def to_eng_string(self, context=None):
01030         """Convert to engineering-type string.
01031 
01032         Engineering notation has an exponent which is a multiple of 3, so there
01033         are up to 3 digits left of the decimal place.
01034 
01035         Same rules for when in exponential and when as a value as in __str__.
01036         """
01037         return self.__str__(eng=True, context=context)

Here is the call graph for this function:

def decimal.Decimal.to_integral_exact (   self,
  rounding = None,
  context = None 
)
Rounds to a nearby integer.

If no rounding mode is specified, take the rounding mode from
the context.  This method raises the Rounded and Inexact flags
when appropriate.

See also: to_integral_value, which does exactly the same as
this method except that it doesn't raise Inexact or Rounded.

Definition at line 2596 of file decimal.py.

02596 
02597     def to_integral_exact(self, rounding=None, context=None):
02598         """Rounds to a nearby integer.
02599 
02600         If no rounding mode is specified, take the rounding mode from
02601         the context.  This method raises the Rounded and Inexact flags
02602         when appropriate.
02603 
02604         See also: to_integral_value, which does exactly the same as
02605         this method except that it doesn't raise Inexact or Rounded.
02606         """
02607         if self._is_special:
02608             ans = self._check_nans(context=context)
02609             if ans:
02610                 return ans
02611             return Decimal(self)
02612         if self._exp >= 0:
02613             return Decimal(self)
02614         if not self:
02615             return _dec_from_triple(self._sign, '0', 0)
02616         if context is None:
02617             context = getcontext()
02618         if rounding is None:
02619             rounding = context.rounding
02620         ans = self._rescale(0, rounding)
02621         if ans != self:
02622             context._raise_error(Inexact)
02623         context._raise_error(Rounded)
02624         return ans

Here is the call graph for this function:

def decimal.Decimal.to_integral_value (   self,
  rounding = None,
  context = None 
)
Rounds to the nearest integer, without raising inexact, rounded.

Definition at line 2625 of file decimal.py.

02625 
02626     def to_integral_value(self, rounding=None, context=None):
02627         """Rounds to the nearest integer, without raising inexact, rounded."""
02628         if context is None:
02629             context = getcontext()
02630         if rounding is None:
02631             rounding = context.rounding
02632         if self._is_special:
02633             ans = self._check_nans(context=context)
02634             if ans:
02635                 return ans
02636             return Decimal(self)
02637         if self._exp >= 0:
02638             return Decimal(self)
02639         else:
02640             return self._rescale(0, rounding)

Here is the call graph for this function:

Here is the caller graph for this function:


Member Data Documentation

decimal.Decimal.__radd__ = __add__ [static, private]

Definition at line 1189 of file decimal.py.

decimal.Decimal.__rmul__ = __mul__ [static, private]

Definition at line 1268 of file decimal.py.

tuple decimal.Decimal.__slots__ = ('_exp','_int','_sign', '_is_special') [static, private]

Definition at line 511 of file decimal.py.

decimal.Decimal.__trunc__ = __int__ [static, private]

Definition at line 1573 of file decimal.py.

Definition at line 562 of file decimal.py.

Definition at line 561 of file decimal.py.

Definition at line 563 of file decimal.py.

tuple decimal.Decimal._pick_rounding_function [static, private]
Initial value:
dict(
        ROUND_DOWN = _round_down,
        ROUND_UP = _round_up,
        ROUND_HALF_UP = _round_half_up,
        ROUND_HALF_DOWN = _round_half_down,
        ROUND_HALF_EVEN = _round_half_even,
        ROUND_CEILING = _round_ceiling,
        ROUND_FLOOR = _round_floor,
        ROUND_05UP = _round_05up,
    )

Definition at line 1759 of file decimal.py.

Definition at line 553 of file decimal.py.

Definition at line 700 of file decimal.py.

Definition at line 107 of file object.h.

struct _typeobject* _object::ob_type [inherited]

Definition at line 108 of file object.h.

Definition at line 2642 of file decimal.py.


Property Documentation

decimal.Decimal.imag = property(imag) [static]

Definition at line 1581 of file decimal.py.

decimal.Decimal.real = property(real) [static]

Definition at line 1577 of file decimal.py.


The documentation for this class was generated from the following file: