Back to index

python3.2  3.2.2
Classes | Functions | Variables
decimal Namespace Reference

Classes

class  DecimalException
class  Clamped
class  InvalidOperation
class  ConversionSyntax
class  DivisionByZero
class  DivisionImpossible
class  DivisionUndefined
class  Inexact
class  InvalidContext
class  Rounded
class  Subnormal
class  Overflow
class  Underflow
class  MockThreading
class  Decimal
 Decimal class #######################################################. More...
class  _ContextManager
 Context class #######################################################. More...
class  Context
class  _WorkRep
class  _Log10Memoize

Functions

def setcontext
def getcontext
def getcontext
def setcontext
def localcontext
def _dec_from_triple
def _normalize
def _sqrt_nearest
def _rshift_nearest
def _div_nearest
def _ilog
def _dlog10
def _dlog
def _iexp
def _dexp
def _dpower
def _log10_lb
def _convert_other
 Helper Functions ####################################################.
def _convert_for_comparison
def _parse_format_specifier
def _format_align
def _group_lengths
def _insert_thousands_sep
def _format_sign
def _format_number

Variables

list __all__
string __version__ = '1.70'
tuple DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')
string ROUND_DOWN = 'ROUND_DOWN'
string ROUND_HALF_UP = 'ROUND_HALF_UP'
string ROUND_HALF_EVEN = 'ROUND_HALF_EVEN'
string ROUND_CEILING = 'ROUND_CEILING'
string ROUND_FLOOR = 'ROUND_FLOOR'
string ROUND_UP = 'ROUND_UP'
string ROUND_HALF_DOWN = 'ROUND_HALF_DOWN'
string ROUND_05UP = 'ROUND_05UP'
list _signals
dictionary _condition_map
tuple local = threading.local()
 _nbits = int.bit_length
 Integer arithmetic functions used by ln, log10, exp and pow #####.
tuple _log10_digits = _Log10Memoize()
tuple DefaultContext
 Setup Specific Contexts ############################################.
tuple BasicContext
tuple ExtendedContext
tuple _parser = re.compile(r""" # A numeric string consists of:# \s* (?P<sign>[-+])? # an optional sign, followed by either... ( (?=\d|\.\d) # ...a number (with at least one digit) (?P<int>\d*) # having a (possibly empty) integer part (\.(?P<frac>\d*))? # followed by an optional fractional part (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... | Inf(inity)? # ...an infinity, or... | (?P<signal>s)? # ...an (optionally signaling) NaN # NaN (?P<diag>\d*) # with (possibly empty) diagnostic info. )# \s* \Z""", re.VERBOSE | re.IGNORECASE)
tuple _all_zeros = re.compile('0*$')
tuple _exact_half = re.compile('50*$')
tuple _parse_format_specifier_regex = re.compile(r"""\A(?: (?P<fill>.)? (?P<align>[<>=^]))?(?P<sign>[-+ ])?(?P<alt>\#)?(?P<zeropad>0)?(?P<minimumwidth>(?!0)\d+)?(?P<thousands_sep>,)?(?:\.(?P<precision>0|(?!0)\d+))?(?P<type>[eEfFgGn%])?\Z""", re.VERBOSE)
 PEP3101 support functions ############################################## The functions in this section have little to do with the Decimal class, and could potentially be reused or adapted for other pure Python numeric classes that want to implement format
tuple _Infinity = Decimal('Inf')
 Useful Constants (internal use only) ################################.
tuple _NegativeInfinity = Decimal('-Inf')
tuple _NaN = Decimal('NaN')
tuple _Zero = Decimal(0)
tuple _One = Decimal(1)
tuple _NegativeOne = Decimal(-1)
tuple _SignedInfinity = (_Infinity, _NegativeInfinity)
 _PyHASH_MODULUS = sys.hash_info.modulus
 _PyHASH_INF = sys.hash_info.inf
 _PyHASH_NAN = sys.hash_info.nan
tuple _PyHASH_10INV = pow(10, _PyHASH_MODULUS - 2, _PyHASH_MODULUS)
 _sign
 _int
 _exp
 _is_special

Function Documentation

def decimal._convert_for_comparison (   self,
  other,
  equality_op = False 
) [private]
Given a Decimal instance self and a Python object other, return
a pair (s, o) of Decimal instances such that "s op o" is
equivalent to "self op other" for any of the 6 comparison
operators "op".

Definition at line 5871 of file decimal.py.

05871 
05872 def _convert_for_comparison(self, other, equality_op=False):
05873     """Given a Decimal instance self and a Python object other, return
05874     a pair (s, o) of Decimal instances such that "s op o" is
05875     equivalent to "self op other" for any of the 6 comparison
05876     operators "op".
05877 
05878     """
05879     if isinstance(other, Decimal):
05880         return self, other
05881 
05882     # Comparison with a Rational instance (also includes integers):
05883     # self op n/d <=> self*d op n (for n and d integers, d positive).
05884     # A NaN or infinity can be left unchanged without affecting the
05885     # comparison result.
05886     if isinstance(other, _numbers.Rational):
05887         if not self._is_special:
05888             self = _dec_from_triple(self._sign,
05889                                     str(int(self._int) * other.denominator),
05890                                     self._exp)
05891         return self, Decimal(other.numerator)
05892 
05893     # Comparisons with float and complex types.  == and != comparisons
05894     # with complex numbers should succeed, returning either True or False
05895     # as appropriate.  Other comparisons return NotImplemented.
05896     if equality_op and isinstance(other, _numbers.Complex) and other.imag == 0:
05897         other = other.real
05898     if isinstance(other, float):
05899         return self, Decimal.from_float(other)
05900     return NotImplemented, NotImplemented
05901 

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._convert_other (   other,
  raiseit = False,
  allow_float = False 
) [private]

Helper Functions ####################################################.

Convert other to Decimal.

Verifies that it's ok to use in an implicit construction.
If allow_float is true, allow conversion from float;  this
is used in the comparison methods (__eq__ and friends).

Definition at line 5852 of file decimal.py.

05852 
05853 def _convert_other(other, raiseit=False, allow_float=False):
05854     """Convert other to Decimal.
05855 
05856     Verifies that it's ok to use in an implicit construction.
05857     If allow_float is true, allow conversion from float;  this
05858     is used in the comparison methods (__eq__ and friends).
05859 
05860     """
05861     if isinstance(other, Decimal):
05862         return other
05863     if isinstance(other, int):
05864         return Decimal(other)
05865     if allow_float and isinstance(other, float):
05866         return Decimal.from_float(other)
05867 
05868     if raiseit:
05869         raise TypeError("Unable to convert %s to Decimal" % other)
05870     return NotImplemented

def decimal._dec_from_triple (   sign,
  coefficient,
  exponent,
  special = False 
) [private]
Create a decimal instance directly, without any validation,
normalization (e.g. removal of leading zeros) or argument
conversion.

This function is for *internal use only*.

Definition at line 3755 of file decimal.py.

03755 
03756 def _dec_from_triple(sign, coefficient, exponent, special=False):
03757     """Create a decimal instance directly, without any validation,
03758     normalization (e.g. removal of leading zeros) or argument
03759     conversion.
03760 
03761     This function is for *internal use only*.
03762     """
03763 
03764     self = object.__new__(Decimal)
03765     self._sign = sign
03766     self._int = coefficient
03767     self._exp = exponent
03768     self._is_special = special
03769 
03770     return self
03771 
03772 # Register Decimal as a kind of Number (an abstract base class).
03773 # However, do not register it as Real (because Decimals are not
03774 # interoperable with floats).
03775 _numbers.Number.register(Decimal)
03776 

Here is the caller graph for this function:

def decimal._dexp (   c,
  e,
  p 
) [private]
Compute an approximation to exp(c*10**e), with p decimal places of
precision.

Returns integers d, f such that:

  10**(p-1) <= d <= 10**p, and
  (d-1)*10**f < exp(c*10**e) < (d+1)*10**f

In other words, d*10**f is an approximation to exp(c*10**e) with p
digits of precision, and with an error in d of at most 1.  This is
almost, but not quite, the same as the error being < 1ulp: when d
= 10**(p-1) the error could be up to 10 ulp.

Definition at line 5763 of file decimal.py.

05763 
05764 def _dexp(c, e, p):
05765     """Compute an approximation to exp(c*10**e), with p decimal places of
05766     precision.
05767 
05768     Returns integers d, f such that:
05769 
05770       10**(p-1) <= d <= 10**p, and
05771       (d-1)*10**f < exp(c*10**e) < (d+1)*10**f
05772 
05773     In other words, d*10**f is an approximation to exp(c*10**e) with p
05774     digits of precision, and with an error in d of at most 1.  This is
05775     almost, but not quite, the same as the error being < 1ulp: when d
05776     = 10**(p-1) the error could be up to 10 ulp."""
05777 
05778     # we'll call iexp with M = 10**(p+2), giving p+3 digits of precision
05779     p += 2
05780 
05781     # compute log(10) with extra precision = adjusted exponent of c*10**e
05782     extra = max(0, e + len(str(c)) - 1)
05783     q = p + extra
05784 
05785     # compute quotient c*10**e/(log(10)) = c*10**(e+q)/(log(10)*10**q),
05786     # rounding down
05787     shift = e+q
05788     if shift >= 0:
05789         cshift = c*10**shift
05790     else:
05791         cshift = c//10**-shift
05792     quot, rem = divmod(cshift, _log10_digits(q))
05793 
05794     # reduce remainder back to original precision
05795     rem = _div_nearest(rem, 10**extra)
05796 
05797     # error in result of _iexp < 120;  error after division < 0.62
05798     return _div_nearest(_iexp(rem, 10**p), 1000), quot - p + 3

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._div_nearest (   a,
  b 
) [private]
Closest integer to a/b, a and b positive integers; rounds to even
in the case of a tie.

Definition at line 5555 of file decimal.py.

05555 
05556 def _div_nearest(a, b):
05557     """Closest integer to a/b, a and b positive integers; rounds to even
05558     in the case of a tie.
05559 
05560     """
05561     q, r = divmod(a, b)
05562     return q + (2*r + (q&1) > b)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._dlog (   c,
  e,
  p 
) [private]
Given integers c, e and p with c > 0, compute an integer
approximation to 10**p * log(c*10**e), with an absolute error of
at most 1.  Assumes that c*10**e is not exactly 1.

Definition at line 5645 of file decimal.py.

05645 
05646 def _dlog(c, e, p):
05647     """Given integers c, e and p with c > 0, compute an integer
05648     approximation to 10**p * log(c*10**e), with an absolute error of
05649     at most 1.  Assumes that c*10**e is not exactly 1."""
05650 
05651     # Increase precision by 2. The precision increase is compensated
05652     # for at the end with a division by 100.
05653     p += 2
05654 
05655     # rewrite c*10**e as d*10**f with either f >= 0 and 1 <= d <= 10,
05656     # or f <= 0 and 0.1 <= d <= 1.  Then we can compute 10**p * log(c*10**e)
05657     # as 10**p * log(d) + 10**p*f * log(10).
05658     l = len(str(c))
05659     f = e+l - (e+l >= 1)
05660 
05661     # compute approximation to 10**p*log(d), with error < 27
05662     if p > 0:
05663         k = e+p-f
05664         if k >= 0:
05665             c *= 10**k
05666         else:
05667             c = _div_nearest(c, 10**-k)  # error of <= 0.5 in c
05668 
05669         # _ilog magnifies existing error in c by a factor of at most 10
05670         log_d = _ilog(c, 10**p) # error < 5 + 22 = 27
05671     else:
05672         # p <= 0: just approximate the whole thing by 0; error < 2.31
05673         log_d = 0
05674 
05675     # compute approximation to f*10**p*log(10), with error < 11.
05676     if f:
05677         extra = len(str(abs(f)))-1
05678         if p + extra >= 0:
05679             # error in f * _log10_digits(p+extra) < |f| * 1 = |f|
05680             # after division, error < |f|/10**extra + 0.5 < 10 + 0.5 < 11
05681             f_log_ten = _div_nearest(f*_log10_digits(p+extra), 10**extra)
05682         else:
05683             f_log_ten = 0
05684     else:
05685         f_log_ten = 0
05686 
05687     # error in sum < 11+27 = 38; error after division < 0.38 + 0.5 < 1
05688     return _div_nearest(f_log_ten + log_d, 100)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._dlog10 (   c,
  e,
  p 
) [private]
Given integers c, e and p with c > 0, p >= 0, compute an integer
approximation to 10**p * log10(c*10**e), with an absolute error of
at most 1.  Assumes that c*10**e is not exactly 1.

Definition at line 5611 of file decimal.py.

05611 
05612 def _dlog10(c, e, p):
05613     """Given integers c, e and p with c > 0, p >= 0, compute an integer
05614     approximation to 10**p * log10(c*10**e), with an absolute error of
05615     at most 1.  Assumes that c*10**e is not exactly 1."""
05616 
05617     # increase precision by 2; compensate for this by dividing
05618     # final result by 100
05619     p += 2
05620 
05621     # write c*10**e as d*10**f with either:
05622     #   f >= 0 and 1 <= d <= 10, or
05623     #   f <= 0 and 0.1 <= d <= 1.
05624     # Thus for c*10**e close to 1, f = 0
05625     l = len(str(c))
05626     f = e+l - (e+l >= 1)
05627 
05628     if p > 0:
05629         M = 10**p
05630         k = e+p-f
05631         if k >= 0:
05632             c *= 10**k
05633         else:
05634             c = _div_nearest(c, 10**-k)
05635 
05636         log_d = _ilog(c, M) # error < 5 + 22 = 27
05637         log_10 = _log10_digits(p) # error < 1
05638         log_d = _div_nearest(log_d*M, log_10)
05639         log_tenpower = f*M # exact
05640     else:
05641         log_d = 0  # error < 2.31
05642         log_tenpower = _div_nearest(f, 10**-p) # error < 0.5
05643 
05644     return _div_nearest(log_tenpower+log_d, 100)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._dpower (   xc,
  xe,
  yc,
  ye,
  p 
) [private]
Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:

  10**(p-1) <= c <= 10**p, and
  (c-1)*10**e < x**y < (c+1)*10**e

in other words, c*10**e is an approximation to x**y with p digits
of precision, and with an error in c of at most 1.  (This is
almost, but not quite, the same as the error being < 1ulp: when c
== 10**(p-1) we can only guarantee error < 10ulp.)

We assume that: x is positive and not equal to 1, and y is nonzero.

Definition at line 5799 of file decimal.py.

05799 
05800 def _dpower(xc, xe, yc, ye, p):
05801     """Given integers xc, xe, yc and ye representing Decimals x = xc*10**xe and
05802     y = yc*10**ye, compute x**y.  Returns a pair of integers (c, e) such that:
05803 
05804       10**(p-1) <= c <= 10**p, and
05805       (c-1)*10**e < x**y < (c+1)*10**e
05806 
05807     in other words, c*10**e is an approximation to x**y with p digits
05808     of precision, and with an error in c of at most 1.  (This is
05809     almost, but not quite, the same as the error being < 1ulp: when c
05810     == 10**(p-1) we can only guarantee error < 10ulp.)
05811 
05812     We assume that: x is positive and not equal to 1, and y is nonzero.
05813     """
05814 
05815     # Find b such that 10**(b-1) <= |y| <= 10**b
05816     b = len(str(abs(yc))) + ye
05817 
05818     # log(x) = lxc*10**(-p-b-1), to p+b+1 places after the decimal point
05819     lxc = _dlog(xc, xe, p+b+1)
05820 
05821     # compute product y*log(x) = yc*lxc*10**(-p-b-1+ye) = pc*10**(-p-1)
05822     shift = ye-b
05823     if shift >= 0:
05824         pc = lxc*yc*10**shift
05825     else:
05826         pc = _div_nearest(lxc*yc, 10**-shift)
05827 
05828     if pc == 0:
05829         # we prefer a result that isn't exactly 1; this makes it
05830         # easier to compute a correctly rounded result in __pow__
05831         if ((len(str(xc)) + xe >= 1) == (yc > 0)): # if x**y > 1:
05832             coeff, exp = 10**(p-1)+1, 1-p
05833         else:
05834             coeff, exp = 10**p-1, -p
05835     else:
05836         coeff, exp = _dexp(pc, -(p+1), p+1)
05837         coeff = _div_nearest(coeff, 10)
05838         exp += 1
05839 
05840     return coeff, exp

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._format_align (   sign,
  body,
  spec 
) [private]
Given an unpadded, non-aligned numeric string 'body' and sign
string 'sign', add padding and alignment conforming to the given
format specifier dictionary 'spec' (as produced by
parse_format_specifier).

Definition at line 6086 of file decimal.py.

06086 
06087 def _format_align(sign, body, spec):
06088     """Given an unpadded, non-aligned numeric string 'body' and sign
06089     string 'sign', add padding and alignment conforming to the given
06090     format specifier dictionary 'spec' (as produced by
06091     parse_format_specifier).
06092 
06093     """
06094     # how much extra space do we have to play with?
06095     minimumwidth = spec['minimumwidth']
06096     fill = spec['fill']
06097     padding = fill*(minimumwidth - len(sign) - len(body))
06098 
06099     align = spec['align']
06100     if align == '<':
06101         result = sign + body + padding
06102     elif align == '>':
06103         result = padding + sign + body
06104     elif align == '=':
06105         result = sign + padding + body
06106     elif align == '^':
06107         half = len(padding)//2
06108         result = padding[:half] + sign + body + padding[half:]
06109     else:
06110         raise ValueError('Unrecognised alignment field')
06111 
06112     return result

Here is the caller graph for this function:

def decimal._format_number (   is_negative,
  intpart,
  fracpart,
  exp,
  spec 
) [private]
Format a number, given the following data:

is_negative: true if the number is negative, else false
intpart: string of digits that must appear before the decimal point
fracpart: string of digits that must come after the point
exp: exponent, as an integer
spec: dictionary resulting from parsing the format specifier

This function uses the information in spec to:
  insert separators (decimal separator and thousands separators)
  format the sign
  format the exponent
  add trailing '%' for the '%' type
  zero-pad if necessary
  fill and align if necessary

Definition at line 6183 of file decimal.py.

06183 
06184 def _format_number(is_negative, intpart, fracpart, exp, spec):
06185     """Format a number, given the following data:
06186 
06187     is_negative: true if the number is negative, else false
06188     intpart: string of digits that must appear before the decimal point
06189     fracpart: string of digits that must come after the point
06190     exp: exponent, as an integer
06191     spec: dictionary resulting from parsing the format specifier
06192 
06193     This function uses the information in spec to:
06194       insert separators (decimal separator and thousands separators)
06195       format the sign
06196       format the exponent
06197       add trailing '%' for the '%' type
06198       zero-pad if necessary
06199       fill and align if necessary
06200     """
06201 
06202     sign = _format_sign(is_negative, spec)
06203 
06204     if fracpart or spec['alt']:
06205         fracpart = spec['decimal_point'] + fracpart
06206 
06207     if exp != 0 or spec['type'] in 'eE':
06208         echar = {'E': 'E', 'e': 'e', 'G': 'E', 'g': 'e'}[spec['type']]
06209         fracpart += "{0}{1:+}".format(echar, exp)
06210     if spec['type'] == '%':
06211         fracpart += '%'
06212 
06213     if spec['zeropad']:
06214         min_width = spec['minimumwidth'] - len(fracpart) - len(sign)
06215     else:
06216         min_width = 0
06217     intpart = _insert_thousands_sep(intpart, spec, min_width)
06218 
06219     return _format_align(sign, intpart+fracpart, spec)
06220 

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._format_sign (   is_negative,
  spec 
) [private]
Determine sign character.

Definition at line 6173 of file decimal.py.

06173 
06174 def _format_sign(is_negative, spec):
06175     """Determine sign character."""
06176 
06177     if is_negative:
06178         return '-'
06179     elif spec['sign'] in ' +':
06180         return spec['sign']
06181     else:
06182         return ''

Here is the caller graph for this function:

def decimal._group_lengths (   grouping) [private]
Convert a localeconv-style grouping into a (possibly infinite)
iterable of integers representing group lengths.

Definition at line 6113 of file decimal.py.

06113 
06114 def _group_lengths(grouping):
06115     """Convert a localeconv-style grouping into a (possibly infinite)
06116     iterable of integers representing group lengths.
06117 
06118     """
06119     # The result from localeconv()['grouping'], and the input to this
06120     # function, should be a list of integers in one of the
06121     # following three forms:
06122     #
06123     #   (1) an empty list, or
06124     #   (2) nonempty list of positive integers + [0]
06125     #   (3) list of positive integers + [locale.CHAR_MAX], or
06126 
06127     from itertools import chain, repeat
06128     if not grouping:
06129         return []
06130     elif grouping[-1] == 0 and len(grouping) >= 2:
06131         return chain(grouping[:-1], repeat(grouping[-2]))
06132     elif grouping[-1] == _locale.CHAR_MAX:
06133         return grouping[:-1]
06134     else:
06135         raise ValueError('unrecognised format for grouping')

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._iexp (   x,
  M,
  L = 8 
) [private]
Given integers x and M, M > 0, such that x/M is small in absolute
value, compute an integer approximation to M*exp(x/M).  For 0 <=
x/M <= 2.4, the absolute error in the result is bounded by 60 (and
is usually much smaller).

Definition at line 5726 of file decimal.py.

05726 
05727 def _iexp(x, M, L=8):
05728     """Given integers x and M, M > 0, such that x/M is small in absolute
05729     value, compute an integer approximation to M*exp(x/M).  For 0 <=
05730     x/M <= 2.4, the absolute error in the result is bounded by 60 (and
05731     is usually much smaller)."""
05732 
05733     # Algorithm: to compute exp(z) for a real number z, first divide z
05734     # by a suitable power R of 2 so that |z/2**R| < 2**-L.  Then
05735     # compute expm1(z/2**R) = exp(z/2**R) - 1 using the usual Taylor
05736     # series
05737     #
05738     #     expm1(x) = x + x**2/2! + x**3/3! + ...
05739     #
05740     # Now use the identity
05741     #
05742     #     expm1(2x) = expm1(x)*(expm1(x)+2)
05743     #
05744     # R times to compute the sequence expm1(z/2**R),
05745     # expm1(z/2**(R-1)), ... , exp(z/2), exp(z).
05746 
05747     # Find R such that x/2**R/M <= 2**-L
05748     R = _nbits((x<<L)//M)
05749 
05750     # Taylor series.  (2**L)**T > M
05751     T = -int(-10*len(str(M))//(3*L))
05752     y = _div_nearest(x, T)
05753     Mshift = M<<R
05754     for i in range(T-1, 0, -1):
05755         y = _div_nearest(x*(Mshift + y), Mshift * i)
05756 
05757     # Expansion
05758     for k in range(R-1, -1, -1):
05759         Mshift = M<<(k+2)
05760         y = _div_nearest(y*(y+Mshift), Mshift)
05761 
05762     return M+y

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._ilog (   x,
  M,
  L = 8 
) [private]
Integer approximation to M*log(x/M), with absolute error boundable
in terms only of x/M.

Given positive integers x and M, return an integer approximation to
M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
between the approximation and the exact result is at most 22.  For
L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
both cases these are upper bounds on the error; it will usually be
much smaller.

Definition at line 5563 of file decimal.py.

05563 
05564 def _ilog(x, M, L = 8):
05565     """Integer approximation to M*log(x/M), with absolute error boundable
05566     in terms only of x/M.
05567 
05568     Given positive integers x and M, return an integer approximation to
05569     M * log(x/M).  For L = 8 and 0.1 <= x/M <= 10 the difference
05570     between the approximation and the exact result is at most 22.  For
05571     L = 8 and 1.0 <= x/M <= 10.0 the difference is at most 15.  In
05572     both cases these are upper bounds on the error; it will usually be
05573     much smaller."""
05574 
05575     # The basic algorithm is the following: let log1p be the function
05576     # log1p(x) = log(1+x).  Then log(x/M) = log1p((x-M)/M).  We use
05577     # the reduction
05578     #
05579     #    log1p(y) = 2*log1p(y/(1+sqrt(1+y)))
05580     #
05581     # repeatedly until the argument to log1p is small (< 2**-L in
05582     # absolute value).  For small y we can use the Taylor series
05583     # expansion
05584     #
05585     #    log1p(y) ~ y - y**2/2 + y**3/3 - ... - (-y)**T/T
05586     #
05587     # truncating at T such that y**T is small enough.  The whole
05588     # computation is carried out in a form of fixed-point arithmetic,
05589     # with a real number z being represented by an integer
05590     # approximation to z*M.  To avoid loss of precision, the y below
05591     # is actually an integer approximation to 2**R*y*M, where R is the
05592     # number of reductions performed so far.
05593 
05594     y = x-M
05595     # argument reduction; R = number of reductions performed
05596     R = 0
05597     while (R <= L and abs(y) << L-R >= M or
05598            R > L and abs(y) >> R-L >= M):
05599         y = _div_nearest((M*y) << 1,
05600                          M + _sqrt_nearest(M*(M+_rshift_nearest(y, R)), M))
05601         R += 1
05602 
05603     # Taylor series with T terms
05604     T = -int(-10*len(str(M))//(3*L))
05605     yshift = _rshift_nearest(y, R)
05606     w = _div_nearest(M, T)
05607     for k in range(T-1, 0, -1):
05608         w = _div_nearest(M, k) - _div_nearest(yshift*w, M)
05609 
05610     return _div_nearest(w*y, M)

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._insert_thousands_sep (   digits,
  spec,
  min_width = 1 
) [private]
Insert thousands separators into a digit string.

spec is a dictionary whose keys should include 'thousands_sep' and
'grouping'; typically it's the result of parsing the format
specifier using _parse_format_specifier.

The min_width keyword argument gives the minimum length of the
result, which will be padded on the left with zeros if necessary.

If necessary, the zero padding adds an extra '0' on the left to
avoid a leading thousands separator.  For example, inserting
commas every three digits in '123456', with min_width=8, gives
'0,123,456', even though that has length 9.

Definition at line 6136 of file decimal.py.

06136 
06137 def _insert_thousands_sep(digits, spec, min_width=1):
06138     """Insert thousands separators into a digit string.
06139 
06140     spec is a dictionary whose keys should include 'thousands_sep' and
06141     'grouping'; typically it's the result of parsing the format
06142     specifier using _parse_format_specifier.
06143 
06144     The min_width keyword argument gives the minimum length of the
06145     result, which will be padded on the left with zeros if necessary.
06146 
06147     If necessary, the zero padding adds an extra '0' on the left to
06148     avoid a leading thousands separator.  For example, inserting
06149     commas every three digits in '123456', with min_width=8, gives
06150     '0,123,456', even though that has length 9.
06151 
06152     """
06153 
06154     sep = spec['thousands_sep']
06155     grouping = spec['grouping']
06156 
06157     groups = []
06158     for l in _group_lengths(grouping):
06159         if l <= 0:
06160             raise ValueError("group length should be positive")
06161         # max(..., 1) forces at least 1 digit to the left of a separator
06162         l = min(max(len(digits), min_width, 1), l)
06163         groups.append('0'*(l - len(digits)) + digits[-l:])
06164         digits = digits[:-l]
06165         min_width -= l
06166         if not digits and min_width <= 0:
06167             break
06168         min_width -= len(sep)
06169     else:
06170         l = max(len(digits), min_width, 1)
06171         groups.append('0'*(l - len(digits)) + digits[-l:])
06172     return sep.join(reversed(groups))

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal._log10_lb (   c,
  correction = {         '1': 100 
) [private]

Definition at line 5842 of file decimal.py.

05842 
05843         '1': 100, '2': 70, '3': 53, '4': 40, '5': 31,
05844         '6': 23, '7': 16, '8': 10, '9': 5}):
05845     """Compute a lower bound for 100*log10(c) for a positive integer c."""
05846     if c <= 0:
05847         raise ValueError("The argument to _log10_lb should be nonnegative.")
05848     str_c = str(c)
05849     return 100*len(str_c) - correction[str_c[0]]

Here is the caller graph for this function:

def decimal._normalize (   op1,
  op2,
  prec = 0 
) [private]
Normalizes op1, op2 to have the same exp and length of coefficient.

Done during addition.

Definition at line 5500 of file decimal.py.

05500 
05501 def _normalize(op1, op2, prec = 0):
05502     """Normalizes op1, op2 to have the same exp and length of coefficient.
05503 
05504     Done during addition.
05505     """
05506     if op1.exp < op2.exp:
05507         tmp = op2
05508         other = op1
05509     else:
05510         tmp = op1
05511         other = op2
05512 
05513     # Let exp = min(tmp.exp - 1, tmp.adjusted() - precision - 1).
05514     # Then adding 10**exp to tmp has the same effect (after rounding)
05515     # as adding any positive quantity smaller than 10**exp; similarly
05516     # for subtraction.  So if other is smaller than 10**exp we replace
05517     # it with 10**exp.  This avoids tmp.exp - other.exp getting too large.
05518     tmp_len = len(str(tmp.int))
05519     other_len = len(str(other.int))
05520     exp = tmp.exp + min(-1, tmp_len - prec - 2)
05521     if other_len + other.exp - 1 < exp:
05522         other.int = 1
05523         other.exp = exp
05524 
05525     tmp.int *= 10 ** (tmp.exp - other.exp)
05526     tmp.exp = other.exp
05527     return op1, op2

Here is the caller graph for this function:

def decimal._parse_format_specifier (   format_spec,
  _localeconv = None 
) [private]
Parse and validate a format specifier.

Turns a standard numeric format specifier into a dict, with the
following entries:

  fill: fill character to pad field to minimum width
  align: alignment type, either '<', '>', '=' or '^'
  sign: either '+', '-' or ' '
  minimumwidth: nonnegative integer giving minimum width
  zeropad: boolean, indicating whether to pad with zeros
  thousands_sep: string to use as thousands separator, or ''
  grouping: grouping for thousands separators, in format
    used by localeconv
  decimal_point: string to use for decimal point
  precision: nonnegative integer giving precision, or None
  type: one of the characters 'eEfFgG%', or None

Definition at line 6006 of file decimal.py.

06006 
06007 def _parse_format_specifier(format_spec, _localeconv=None):
06008     """Parse and validate a format specifier.
06009 
06010     Turns a standard numeric format specifier into a dict, with the
06011     following entries:
06012 
06013       fill: fill character to pad field to minimum width
06014       align: alignment type, either '<', '>', '=' or '^'
06015       sign: either '+', '-' or ' '
06016       minimumwidth: nonnegative integer giving minimum width
06017       zeropad: boolean, indicating whether to pad with zeros
06018       thousands_sep: string to use as thousands separator, or ''
06019       grouping: grouping for thousands separators, in format
06020         used by localeconv
06021       decimal_point: string to use for decimal point
06022       precision: nonnegative integer giving precision, or None
06023       type: one of the characters 'eEfFgG%', or None
06024 
06025     """
06026     m = _parse_format_specifier_regex.match(format_spec)
06027     if m is None:
06028         raise ValueError("Invalid format specifier: " + format_spec)
06029 
06030     # get the dictionary
06031     format_dict = m.groupdict()
06032 
06033     # zeropad; defaults for fill and alignment.  If zero padding
06034     # is requested, the fill and align fields should be absent.
06035     fill = format_dict['fill']
06036     align = format_dict['align']
06037     format_dict['zeropad'] = (format_dict['zeropad'] is not None)
06038     if format_dict['zeropad']:
06039         if fill is not None:
06040             raise ValueError("Fill character conflicts with '0'"
06041                              " in format specifier: " + format_spec)
06042         if align is not None:
06043             raise ValueError("Alignment conflicts with '0' in "
06044                              "format specifier: " + format_spec)
06045     format_dict['fill'] = fill or ' '
06046     # PEP 3101 originally specified that the default alignment should
06047     # be left;  it was later agreed that right-aligned makes more sense
06048     # for numeric types.  See http://bugs.python.org/issue6857.
06049     format_dict['align'] = align or '>'
06050 
06051     # default sign handling: '-' for negative, '' for positive
06052     if format_dict['sign'] is None:
06053         format_dict['sign'] = '-'
06054 
06055     # minimumwidth defaults to 0; precision remains None if not given
06056     format_dict['minimumwidth'] = int(format_dict['minimumwidth'] or '0')
06057     if format_dict['precision'] is not None:
06058         format_dict['precision'] = int(format_dict['precision'])
06059 
06060     # if format type is 'g' or 'G' then a precision of 0 makes little
06061     # sense; convert it to 1.  Same if format type is unspecified.
06062     if format_dict['precision'] == 0:
06063         if format_dict['type'] is None or format_dict['type'] in 'gG':
06064             format_dict['precision'] = 1
06065 
06066     # determine thousands separator, grouping, and decimal separator, and
06067     # add appropriate entries to format_dict
06068     if format_dict['type'] == 'n':
06069         # apart from separators, 'n' behaves just like 'g'
06070         format_dict['type'] = 'g'
06071         if _localeconv is None:
06072             _localeconv = _locale.localeconv()
06073         if format_dict['thousands_sep'] is not None:
06074             raise ValueError("Explicit thousands separator conflicts with "
06075                              "'n' type in format specifier: " + format_spec)
06076         format_dict['thousands_sep'] = _localeconv['thousands_sep']
06077         format_dict['grouping'] = _localeconv['grouping']
06078         format_dict['decimal_point'] = _localeconv['decimal_point']
06079     else:
06080         if format_dict['thousands_sep'] is None:
06081             format_dict['thousands_sep'] = ''
06082         format_dict['grouping'] = [3, 0]
06083         format_dict['decimal_point'] = '.'
06084 
06085     return format_dict

Here is the caller graph for this function:

def decimal._rshift_nearest (   x,
  shift 
) [private]
Given an integer x and a nonnegative integer shift, return closest
integer to x / 2**shift; use round-to-even in case of a tie.

Definition at line 5547 of file decimal.py.

05547 
05548 def _rshift_nearest(x, shift):
05549     """Given an integer x and a nonnegative integer shift, return closest
05550     integer to x / 2**shift; use round-to-even in case of a tie.
05551 
05552     """
05553     b, q = 1 << shift, x >> shift
05554     return q + (2*(x & (b-1)) + (q&1) > b)

Here is the caller graph for this function:

def decimal._sqrt_nearest (   n,
  a 
) [private]
Closest integer to the square root of the positive integer n.  a is
an initial approximation to the square root.  Any positive integer
will do for a, but the closer a is to the square root of n the
faster convergence will be.

Definition at line 5532 of file decimal.py.

05532 
05533 def _sqrt_nearest(n, a):
05534     """Closest integer to the square root of the positive integer n.  a is
05535     an initial approximation to the square root.  Any positive integer
05536     will do for a, but the closer a is to the square root of n the
05537     faster convergence will be.
05538 
05539     """
05540     if n <= 0 or a <= 0:
05541         raise ValueError("Both arguments to _sqrt_nearest should be positive.")
05542 
05543     b=0
05544     while a != b:
05545         b, a = a, a--n//a>>1
05546     return a

Here is the caller graph for this function:

Returns this thread's context.

If this thread does not yet have a context, returns
a new context and sets this thread's context.
New contexts are copies of DefaultContext.

Definition at line 419 of file decimal.py.

00419 
00420     def getcontext():
00421         """Returns this thread's context.
00422 
00423         If this thread does not yet have a context, returns
00424         a new context and sets this thread's context.
00425         New contexts are copies of DefaultContext.
00426         """
00427         try:
00428             return threading.current_thread().__decimal_context__
00429         except AttributeError:
00430             context = Context()
00431             threading.current_thread().__decimal_context__ = context
00432             return context
00433 
00434 else:

Here is the call graph for this function:

def decimal.getcontext (   _local = local)
Returns this thread's context.

If this thread does not yet have a context, returns
a new context and sets this thread's context.
New contexts are copies of DefaultContext.

Definition at line 439 of file decimal.py.

00439 
00440     def getcontext(_local=local):
00441         """Returns this thread's context.
00442 
00443         If this thread does not yet have a context, returns
00444         a new context and sets this thread's context.
00445         New contexts are copies of DefaultContext.
00446         """
00447         try:
00448             return _local.__decimal_context__
00449         except AttributeError:
00450             context = Context()
00451             _local.__decimal_context__ = context
00452             return context

Here is the call graph for this function:

def decimal.localcontext (   ctx = None)
Return a context manager for a copy of the supplied context

Uses a copy of the current context if no context is specified
The returned context manager creates a local decimal context
in a with statement:
    def sin(x):
         with localcontext() as ctx:
             ctx.prec += 2
             # Rest of sin calculation algorithm
             # uses a precision 2 greater than normal
         return +s  # Convert result to normal precision

     def sin(x):
         with localcontext(ExtendedContext):
             # Rest of sin calculation algorithm
             # uses the Extended Context from the
             # General Decimal Arithmetic Specification
         return +s  # Convert result to normal context

>>> setcontext(DefaultContext)
>>> print(getcontext().prec)
28
>>> with localcontext():
...     ctx = getcontext()
...     ctx.prec += 2
...     print(ctx.prec)
...
30
>>> with localcontext(ExtendedContext):
...     print(getcontext().prec)
...
9
>>> print(getcontext().prec)
28

Definition at line 462 of file decimal.py.

00462 
00463 def localcontext(ctx=None):
00464     """Return a context manager for a copy of the supplied context
00465 
00466     Uses a copy of the current context if no context is specified
00467     The returned context manager creates a local decimal context
00468     in a with statement:
00469         def sin(x):
00470              with localcontext() as ctx:
00471                  ctx.prec += 2
00472                  # Rest of sin calculation algorithm
00473                  # uses a precision 2 greater than normal
00474              return +s  # Convert result to normal precision
00475 
00476          def sin(x):
00477              with localcontext(ExtendedContext):
00478                  # Rest of sin calculation algorithm
00479                  # uses the Extended Context from the
00480                  # General Decimal Arithmetic Specification
00481              return +s  # Convert result to normal context
00482 
00483     >>> setcontext(DefaultContext)
00484     >>> print(getcontext().prec)
00485     28
00486     >>> with localcontext():
00487     ...     ctx = getcontext()
00488     ...     ctx.prec += 2
00489     ...     print(ctx.prec)
00490     ...
00491     30
00492     >>> with localcontext(ExtendedContext):
00493     ...     print(getcontext().prec)
00494     ...
00495     9
00496     >>> print(getcontext().prec)
00497     28
00498     """
00499     if ctx is None: ctx = getcontext()
00500     return _ContextManager(ctx)
00501 

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.setcontext (   context)
Set this thread's context to context.

Definition at line 412 of file decimal.py.

00412 
00413     def setcontext(context):
00414         """Set this thread's context to context."""
00415         if context in (DefaultContext, BasicContext, ExtendedContext):
00416             context = context.copy()
00417             context.clear_flags()
00418         threading.current_thread().__decimal_context__ = context

Here is the call graph for this function:

Here is the caller graph for this function:

def decimal.setcontext (   context,
  _local = local 
)
Set this thread's context to context.

Definition at line 453 of file decimal.py.

00453 
00454     def setcontext(context, _local=local):
00455         """Set this thread's context to context."""
00456         if context in (DefaultContext, BasicContext, ExtendedContext):
00457             context = context.copy()
00458             context.clear_flags()
00459         _local.__decimal_context__ = context

Here is the call graph for this function:


Variable Documentation

Initial value:
00001 [
00002     # Two major classes
00003     'Decimal', 'Context',
00004 
00005     # Contexts
00006     'DefaultContext', 'BasicContext', 'ExtendedContext',
00007 
00008     # Exceptions
00009     'DecimalException', 'Clamped', 'InvalidOperation', 'DivisionByZero',
00010     'Inexact', 'Rounded', 'Subnormal', 'Overflow', 'Underflow',
00011 
00012     # Constants for use in setting up contexts
00013     'ROUND_DOWN', 'ROUND_HALF_UP', 'ROUND_HALF_EVEN', 'ROUND_CEILING',
00014     'ROUND_FLOOR', 'ROUND_UP', 'ROUND_HALF_DOWN', 'ROUND_05UP',
00015 
00016     # Functions for manipulating contexts
00017     'setcontext', 'getcontext', 'localcontext'
00018 ]

Definition at line 115 of file decimal.py.

Definition at line 134 of file decimal.py.

Definition at line 5969 of file decimal.py.

Initial value:
00001 {ConversionSyntax:InvalidOperation,
00002                   DivisionImpossible:InvalidOperation,
00003                   DivisionUndefined:InvalidOperation,
00004                   InvalidContext:InvalidOperation}

Definition at line 378 of file decimal.py.

Definition at line 5970 of file decimal.py.

Definition at line 3766 of file decimal.py.

tuple decimal._Infinity = Decimal('Inf')

Useful Constants (internal use only) ################################.

Definition at line 6224 of file decimal.py.

Definition at line 3765 of file decimal.py.

Definition at line 3767 of file decimal.py.

Definition at line 5724 of file decimal.py.

tuple decimal._NaN = Decimal('NaN')

Definition at line 6226 of file decimal.py.

Integer arithmetic functions used by ln, log10, exp and pow #####.

Definition at line 5530 of file decimal.py.

Definition at line 6225 of file decimal.py.

Definition at line 6229 of file decimal.py.

tuple decimal._One = Decimal(1)

Definition at line 6228 of file decimal.py.

tuple decimal._parse_format_specifier_regex = re.compile(r"""\A(?: (?P<fill>.)? (?P<align>[<>=^]))?(?P<sign>[-+ ])?(?P<alt>\#)?(?P<zeropad>0)?(?P<minimumwidth>(?!0)\d+)?(?P<thousands_sep>,)?(?:\.(?P<precision>0|(?!0)\d+))?(?P<type>[eEfFgGn%])?\Z""", re.VERBOSE)

PEP3101 support functions ############################################## The functions in this section have little to do with the Decimal class, and could potentially be reused or adapted for other pure Python numeric classes that want to implement format

A format specifier for Decimal looks like:

[[fill]align][sign][#][0][minimumwidth][,][.precision][type]

Definition at line 5981 of file decimal.py.

tuple decimal._parser = re.compile(r""" # A numeric string consists of:# \s* (?P<sign>[-+])? # an optional sign, followed by either... ( (?=\d|\.\d) # ...a number (with at least one digit) (?P<int>\d*) # having a (possibly empty) integer part (\.(?P<frac>\d*))? # followed by an optional fractional part (E(?P<exp>[-+]?\d+))? # followed by an optional exponent, or... | Inf(inity)? # ...an infinity, or... | (?P<signal>s)? # ...an (optionally signaling) NaN # NaN (?P<diag>\d*) # with (possibly empty) diagnostic info. )# \s* \Z""", re.VERBOSE | re.IGNORECASE)

Definition at line 5950 of file decimal.py.

Definition at line 6244 of file decimal.py.

decimal._PyHASH_INF = sys.hash_info.inf

Definition at line 6239 of file decimal.py.

decimal._PyHASH_MODULUS = sys.hash_info.modulus

Definition at line 6237 of file decimal.py.

decimal._PyHASH_NAN = sys.hash_info.nan

Definition at line 6240 of file decimal.py.

Definition at line 3764 of file decimal.py.

Initial value:
00001 [Clamped, DivisionByZero, Inexact, Overflow, Rounded,
00002            Underflow, InvalidOperation, Subnormal]

Definition at line 374 of file decimal.py.

Definition at line 6232 of file decimal.py.

tuple decimal._Zero = Decimal(0)

Definition at line 6227 of file decimal.py.

Initial value:
00001 Context(
00002         prec=9, rounding=ROUND_HALF_UP,
00003         traps=[DivisionByZero, Overflow, InvalidOperation, Clamped, Underflow],
00004         flags=[],
00005 )

Definition at line 5922 of file decimal.py.

decimal.DecimalTuple = _namedtuple('DecimalTuple', 'sign digits exponent')

Definition at line 143 of file decimal.py.

Initial value:
00001 Context(
00002         prec=28, rounding=ROUND_HALF_EVEN,
00003         traps=[DivisionByZero, Overflow, InvalidOperation],
00004         flags=[],
00005         Emax=999999999,
00006         Emin=-999999999,
00007         capitals=1,
00008         clamp=0
00009 )

Setup Specific Contexts ############################################.

Definition at line 5907 of file decimal.py.

Initial value:
00001 Context(
00002         prec=9, rounding=ROUND_HALF_EVEN,
00003         traps=[],
00004         flags=[],
00005 )

Definition at line 5928 of file decimal.py.

Definition at line 435 of file decimal.py.

Definition at line 155 of file decimal.py.

Definition at line 151 of file decimal.py.

Definition at line 148 of file decimal.py.

Definition at line 152 of file decimal.py.

Definition at line 154 of file decimal.py.

Definition at line 150 of file decimal.py.

Definition at line 149 of file decimal.py.

Definition at line 153 of file decimal.py.