1313 lines · 46.8 KB · TeX
RawDownload
\section{\module{decimal} ---         Decimal floating point arithmetic} \declaremodule{standard}{decimal}\modulesynopsis{Implementation of the General Decimal Arithmetic Specification.} \moduleauthor{Eric Price}{eprice at tjhsst.edu}\moduleauthor{Facundo Batista}{facundo at taniquetil.com.ar}\moduleauthor{Raymond Hettinger}{python at rcn.com}\moduleauthor{Aahz}{aahz at pobox.com}\moduleauthor{Tim Peters}{tim.one at comcast.net} \sectionauthor{Raymond D. Hettinger}{python at rcn.com} \versionadded{2.4} The \module{decimal} module provides support for decimal floating pointarithmetic.  It offers several advantages over the \class{float()} datatype: \begin{itemize} \item Decimal numbers can be represented exactly.  In contrast, numbers like\constant{1.1} do not have an exact representation in binary floating point.End users typically would not expect \constant{1.1} to display as\constant{1.1000000000000001} as it does with binary floating point. \item The exactness carries over into arithmetic.  In decimal floating point,\samp{0.1 + 0.1 + 0.1 - 0.3} is exactly equal to zero.  In binary floatingpoint, result is \constant{5.5511151231257827e-017}.  While near to zero, thedifferences prevent reliable equality testing and differences can accumulate.For this reason, decimal would be preferred in accounting applications whichhave strict equality invariants. \item The decimal module incorporates a notion of significant places so that\samp{1.30 + 1.20} is \constant{2.50}.  The trailing zero is kept to indicatesignificance.  This is the customary presentation for monetary applications. Formultiplication, the ``schoolbook'' approach uses all the figures in themultiplicands.  For instance, \samp{1.3 * 1.2} gives \constant{1.56} while\samp{1.30 * 1.20} gives \constant{1.5600}. \item Unlike hardware based binary floating point, the decimal module has a usersettable precision (defaulting to 28 places) which can be as large as needed fora given problem: \begin{verbatim}>>> getcontext().prec = 6>>> Decimal(1) / Decimal(7)Decimal("0.142857")>>> getcontext().prec = 28>>> Decimal(1) / Decimal(7)Decimal("0.1428571428571428571428571429")\end{verbatim} \item Both binary and decimal floating point are implemented in terms of publishedstandards.  While the built-in float type exposes only a modest portion of itscapabilities, the decimal module exposes all required parts of the standard.When needed, the programmer has full control over rounding and signal handling. \end{itemize}  The module design is centered around three concepts:  the decimal number, thecontext for arithmetic, and signals. A decimal number is immutable.  It has a sign, coefficient digits, and anexponent.  To preserve significance, the coefficient digits do not truncatetrailing zeroes.  Decimals also include special values such as\constant{Infinity}, \constant{-Infinity}, and \constant{NaN}.  The standardalso differentiates \constant{-0} from \constant{+0}.                                                   The context for arithmetic is an environment specifying precision, roundingrules, limits on exponents, flags indicating the results of operations,and trap enablers which determine whether signals are treated asexceptions.  Rounding options include \constant{ROUND_CEILING},\constant{ROUND_DOWN}, \constant{ROUND_FLOOR}, \constant{ROUND_HALF_DOWN},\constant{ROUND_HALF_EVEN}, \constant{ROUND_HALF_UP}, and \constant{ROUND_UP}. Signals are groups of exceptional conditions arising during the course ofcomputation.  Depending on the needs of the application, signals may beignored, considered as informational, or treated as exceptions. The signals inthe decimal module are: \constant{Clamped}, \constant{InvalidOperation},\constant{DivisionByZero}, \constant{Inexact}, \constant{Rounded},\constant{Subnormal}, \constant{Overflow}, and \constant{Underflow}. For each signal there is a flag and a trap enabler.  When a signal isencountered, its flag is incremented from zero and, then, if the trap enableris set to one, an exception is raised.  Flags are sticky, so the userneeds to reset them before monitoring a calculation.  \begin{seealso}  \seetext{IBM's General Decimal Arithmetic Specification,           \citetitle[http://www2.hursley.ibm.com/decimal/decarith.html]           {The General Decimal Arithmetic Specification}.}   \seetext{IEEE standard 854-1987,           \citetitle[http://www.cs.berkeley.edu/\textasciitilde ejr/projects/754/private/drafts/854-1987/dir.html]           {Unofficial IEEE 854 Text}.} \end{seealso}   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\subsection{Quick-start Tutorial \label{decimal-tutorial}} The usual start to using decimals is importing the module, viewing the currentcontext with \function{getcontext()} and, if necessary, setting new valuesfor precision, rounding, or enabled traps: \begin{verbatim}>>> from decimal import *>>> getcontext()Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,        capitals=1, flags=[], traps=[Overflow, InvalidOperation,        DivisionByZero]) >>> getcontext().prec = 7       # Set a new precision\end{verbatim}  Decimal instances can be constructed from integers, strings, or tuples.  Tocreate a Decimal from a \class{float}, first convert it to a string.  Thisserves as an explicit reminder of the details of the conversion (includingrepresentation error).  Decimal numbers include special values such as\constant{NaN} which stands for ``Not a number'', positive and negative\constant{Infinity}, and \constant{-0}.         \begin{verbatim}>>> Decimal(10)Decimal("10")>>> Decimal("3.14")Decimal("3.14")>>> Decimal((0, (3, 1, 4), -2))Decimal("3.14")>>> Decimal(str(2.0 ** 0.5))Decimal("1.41421356237")>>> Decimal("NaN")Decimal("NaN")>>> Decimal("-Infinity")Decimal("-Infinity")\end{verbatim}  The significance of a new Decimal is determined solely by the numberof digits input.  Context precision and rounding only come into play duringarithmetic operations. \begin{verbatim}>>> getcontext().prec = 6>>> Decimal('3.0')Decimal("3.0")>>> Decimal('3.1415926535')Decimal("3.1415926535")>>> Decimal('3.1415926535') + Decimal('2.7182818285')Decimal("5.85987")>>> getcontext().rounding = ROUND_UP>>> Decimal('3.1415926535') + Decimal('2.7182818285')Decimal("5.85988")\end{verbatim}  Decimals interact well with much of the rest of Python.  Here is a smalldecimal floating point flying circus:    \begin{verbatim}    >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())>>> max(data)Decimal("9.25")>>> min(data)Decimal("0.03")>>> sorted(data)[Decimal("0.03"), Decimal("1.00"), Decimal("1.34"), Decimal("1.87"), Decimal("2.35"), Decimal("3.45"), Decimal("9.25")]>>> sum(data)Decimal("19.29")>>> a,b,c = data[:3]>>> str(a)'1.34'>>> float(a)1.3400000000000001>>> round(a, 1)     # round() first converts to binary floating point1.3>>> int(a)1>>> a * 5Decimal("6.70")>>> a * bDecimal("2.5058")>>> c % aDecimal("0.77")\end{verbatim} The \method{quantize()} method rounds a number to a fixed exponent.  Thismethod is useful for monetary applications that often round results to a fixednumber of places: \begin{verbatim} >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)Decimal("7.32")>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)Decimal("8")\end{verbatim} As shown above, the \function{getcontext()} function accesses the currentcontext and allows the settings to be changed.  This approach meets theneeds of most applications. For more advanced work, it may be useful to create alternate contexts usingthe Context() constructor.  To make an alternate active, use the\function{setcontext()} function. In accordance with the standard, the \module{Decimal} module provides twoready to use standard contexts, \constant{BasicContext} and\constant{ExtendedContext}. The former is especially useful for debuggingbecause many of the traps are enabled: \begin{verbatim}>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)>>> setcontext(myothercontext)>>> Decimal(1) / Decimal(7)Decimal("0.142857142857142857142857142857142857142857142857142857142857") >>> ExtendedContextContext(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,        capitals=1, flags=[], traps=[])>>> setcontext(ExtendedContext)>>> Decimal(1) / Decimal(7)Decimal("0.142857143")>>> Decimal(42) / Decimal(0)Decimal("Infinity") >>> setcontext(BasicContext)>>> Decimal(42) / Decimal(0)Traceback (most recent call last):  File "<pyshell#143>", line 1, in -toplevel-    Decimal(42) / Decimal(0)DivisionByZero: x / 0\end{verbatim}  Contexts also have signal flags for monitoring exceptional conditionsencountered during computations.  The flags remain set until explicitlycleared, so it is best to clear the flags before each set of monitoredcomputations by using the \method{clear_flags()} method. \begin{verbatim}>>> setcontext(ExtendedContext)>>> getcontext().clear_flags()>>> Decimal(355) / Decimal(113)Decimal("3.14159292")>>> getcontext()Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,        capitals=1, flags=[Inexact, Rounded], traps=[])\end{verbatim} The \var{flags} entry shows that the rational approximation to \constant{Pi}was rounded (digits beyond the context precision were thrown away) and thatthe result is inexact (some of the discarded digits were non-zero). Individual traps are set using the dictionary in the \member{traps}field of a context: \begin{verbatim}>>> Decimal(1) / Decimal(0)Decimal("Infinity")>>> getcontext().traps[DivisionByZero] = 1>>> Decimal(1) / Decimal(0)Traceback (most recent call last):  File "<pyshell#112>", line 1, in -toplevel-    Decimal(1) / Decimal(0)DivisionByZero: x / 0\end{verbatim} Most programs adjust the current context only once, at the beginning of theprogram.  And, in many applications, data is converted to \class{Decimal} witha single cast inside a loop.  With context set and decimals created, the bulkof the program manipulates the data no differently than with other Pythonnumeric types.   %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\subsection{Decimal objects \label{decimal-decimal}} \begin{classdesc}{Decimal}{\optional{value \optional{, context}}}  Constructs a new \class{Decimal} object based from \var{value}.   \var{value} can be an integer, string, tuple, or another \class{Decimal}  object. If no \var{value} is given, returns \code{Decimal("0")}.  If  \var{value} is a string, it should conform to the decimal numeric string  syntax:      \begin{verbatim}    sign           ::=  '+' | '-'    digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'    indicator      ::=  'e' | 'E'    digits         ::=  digit [digit]...    decimal-part   ::=  digits '.' [digits] | ['.'] digits    exponent-part  ::=  indicator [sign] digits    infinity       ::=  'Infinity' | 'Inf'    nan            ::=  'NaN' [digits] | 'sNaN' [digits]    numeric-value  ::=  decimal-part [exponent-part] | infinity    numeric-string ::=  [sign] numeric-value | [sign] nan    \end{verbatim}   If \var{value} is a \class{tuple}, it should have three components,  a sign (\constant{0} for positive or \constant{1} for negative),  a \class{tuple} of digits, and an integer exponent. For example,  \samp{Decimal((0, (1, 4, 1, 4), -3))} returns \code{Decimal("1.414")}.   The \var{context} precision does not affect how many digits are stored.  That is determined exclusively by the number of digits in \var{value}. For  example, \samp{Decimal("3.00000")} records all five zeroes even if the  context precision is only three.   The purpose of the \var{context} argument is determining what to do if  \var{value} is a malformed string.  If the context traps  \constant{InvalidOperation}, an exception is raised; otherwise, the  constructor returns a new Decimal with the value of \constant{NaN}.   Once constructed, \class{Decimal} objects are immutable.\end{classdesc} Decimal floating point objects share many properties with the other builtinnumeric types such as \class{float} and \class{int}.  All of the usualmath operations and special methods apply.  Likewise, decimal objects canbe copied, pickled, printed, used as dictionary keys, used as set elements,compared, sorted, and coerced to another type (such as \class{float}or \class{long}). In addition to the standard numeric properties, decimal floating point objectsalso have a number of specialized methods: \begin{methoddesc}{adjusted}{}  Return the adjusted exponent after shifting out the coefficient's rightmost  digits until only the lead digit remains: \code{Decimal("321e+5").adjusted()}  returns seven.  Used for determining the position of the most significant  digit with respect to the decimal point.\end{methoddesc} \begin{methoddesc}{as_tuple}{}  Returns a tuple representation of the number:  \samp{(sign, digittuple, exponent)}.\end{methoddesc} \begin{methoddesc}{compare}{other\optional{, context}}  Compares like \method{__cmp__()} but returns a decimal instance:  \begin{verbatim}        a or b is a NaN ==> Decimal("NaN")        a < b           ==> Decimal("-1")        a == b          ==> Decimal("0")        a > b           ==> Decimal("1")  \end{verbatim}\end{methoddesc} \begin{methoddesc}{max}{other\optional{, context}}  Like \samp{max(self, other)} except that the context rounding rule  is applied before returning and that \constant{NaN} values are  either signalled or ignored (depending on the context and whether  they are signaling or quiet).\end{methoddesc} \begin{methoddesc}{min}{other\optional{, context}}  Like \samp{min(self, other)} except that the context rounding rule  is applied before returning and that \constant{NaN} values are  either signalled or ignored (depending on the context and whether  they are signaling or quiet).\end{methoddesc} \begin{methoddesc}{normalize}{\optional{context}}  Normalize the number by stripping the rightmost trailing zeroes and  converting any result equal to \constant{Decimal("0")} to  \constant{Decimal("0e0")}. Used for producing canonical values for members  of an equivalence class. For example, \code{Decimal("32.100")} and  \code{Decimal("0.321000e+2")} both normalize to the equivalent value  \code{Decimal("32.1")}.\end{methoddesc}                                               \begin{methoddesc}{quantize}  {exp \optional{, rounding\optional{, context\optional{, watchexp}}}}  Quantize makes the exponent the same as \var{exp}.  Searches for a  rounding method in \var{rounding}, then in \var{context}, and then  in the current context.   If \var{watchexp} is set (default), then an error is returned whenever  the resulting exponent is greater than \member{Emax} or less than  \member{Etiny}.\end{methoddesc}  \begin{methoddesc}{remainder_near}{other\optional{, context}}  Computes the modulo as either a positive or negative value depending  on which is closest to zero.  For instance,  \samp{Decimal(10).remainder_near(6)} returns \code{Decimal("-2")}  which is closer to zero than \code{Decimal("4")}.   If both are equally close, the one chosen will have the same sign  as \var{self}.\end{methoddesc}   \begin{methoddesc}{same_quantum}{other\optional{, context}}  Test whether self and other have the same exponent or whether both  are \constant{NaN}.\end{methoddesc} \begin{methoddesc}{sqrt}{\optional{context}}  Return the square root to full precision.\end{methoddesc}                     \begin{methoddesc}{to_eng_string}{\optional{context}}  Convert to an 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.  For example, converts  \code{Decimal('123E+1')} to \code{Decimal("1.23E+3")}\end{methoddesc}   \begin{methoddesc}{to_integral}{\optional{rounding\optional{, context}}}                     Rounds to the nearest integer without signaling \constant{Inexact}  or \constant{Rounded}.  If given, applies \var{rounding}; otherwise,  uses the rounding method in either the supplied \var{context} or the  current context.\end{methoddesc}    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%            \subsection{Context objects \label{decimal-decimal}} Contexts are environments for arithmetic operations.  They govern precision,set rules for rounding, determine which signals are treated as exceptions, andlimit the range for exponents. Each thread has its own current context which is accessed or changed usingthe \function{getcontext()} and \function{setcontext()} functions: \begin{funcdesc}{getcontext}{}  Return the current context for the active thread.\end{funcdesc}             \begin{funcdesc}{setcontext}{c}  Set the current context for the active thread to \var{c}.\end{funcdesc}   Beginning with Python 2.5, you can also use the \keyword{with} statementand the \function{localcontext()} function to temporarily change theactive context. \begin{funcdesc}{localcontext}{\optional{c}}  Return a context manager that will set the current context for  the active thread to a copy of \var{c} on entry to the with-statement  and restore the previous context when exiting the with-statement. If  no context is specified, a copy of the current context is used.  \versionadded{2.5}   For example, the following code sets the current decimal precision  to 42 places, performs a calculation, and then automatically restores  the previous context:\begin{verbatim}    from __future__ import with_statement    from decimal import localcontext     with localcontext() as ctx:        ctx.prec = 42   # Perform a high precision calculation        s = calculate_something()    s = +s  # Round the final result back to the default precision\end{verbatim}\end{funcdesc} New contexts can also be created using the \class{Context} constructordescribed below. In addition, the module provides three pre-madecontexts: \begin{classdesc*}{BasicContext}  This is a standard context defined by the General Decimal Arithmetic  Specification.  Precision is set to nine.  Rounding is set to  \constant{ROUND_HALF_UP}.  All flags are cleared.  All traps are enabled  (treated as exceptions) except \constant{Inexact}, \constant{Rounded}, and  \constant{Subnormal}.   Because many of the traps are enabled, this context is useful for debugging.\end{classdesc*} \begin{classdesc*}{ExtendedContext}  This is a standard context defined by the General Decimal Arithmetic  Specification.  Precision is set to nine.  Rounding is set to  \constant{ROUND_HALF_EVEN}.  All flags are cleared.  No traps are enabled  (so that exceptions are not raised during computations).   Because the trapped are disabled, this context is useful for applications  that prefer to have result value of \constant{NaN} or \constant{Infinity}  instead of raising exceptions.  This allows an application to complete a  run in the presence of conditions that would otherwise halt the program.\end{classdesc*} \begin{classdesc*}{DefaultContext}  This context is used by the \class{Context} constructor as a prototype for  new contexts.  Changing a field (such a precision) has the effect of  changing the default for new contexts creating by the \class{Context}  constructor.

Lines 1–500 of 1313.