Issue 2188: Documentation hint about disabling proxy detection.
[python.git] / Doc / library / decimal.rst
blob2d2ae938bd1ed3e26edb106a130f9e18929ecb72
2 :mod:`decimal` --- Decimal fixed point and floating point arithmetic
3 ====================================================================
5 .. module:: decimal
6    :synopsis: Implementation of the General Decimal Arithmetic  Specification.
9 .. moduleauthor:: Eric Price <eprice at tjhsst.edu>
10 .. moduleauthor:: Facundo Batista <facundo at taniquetil.com.ar>
11 .. moduleauthor:: Raymond Hettinger <python at rcn.com>
12 .. moduleauthor:: Aahz <aahz at pobox.com>
13 .. moduleauthor:: Tim Peters <tim.one at comcast.net>
16 .. sectionauthor:: Raymond D. Hettinger <python at rcn.com>
19 .. versionadded:: 2.4
21 The :mod:`decimal` module provides support for decimal floating point
22 arithmetic.  It offers several advantages over the :class:`float` datatype:
24 * Decimal "is based on a floating-point model which was designed with people
25   in mind, and necessarily has a paramount guiding principle -- computers must
26   provide an arithmetic that works in the same way as the arithmetic that
27   people learn at school." -- excerpt from the decimal arithmetic specification.
29 * Decimal numbers can be represented exactly.  In contrast, numbers like
30   :const:`1.1` do not have an exact representation in binary floating point. End
31   users typically would not expect :const:`1.1` to display as
32   :const:`1.1000000000000001` as it does with binary floating point.
34 * The exactness carries over into arithmetic.  In decimal floating point, ``0.1
35   + 0.1 + 0.1 - 0.3`` is exactly equal to zero.  In binary floating point, the result
36   is :const:`5.5511151231257827e-017`.  While near to zero, the differences
37   prevent reliable equality testing and differences can accumulate. For this
38   reason, decimal is preferred in accounting applications which have strict
39   equality invariants.
41 * The decimal module incorporates a notion of significant places so that ``1.30
42   + 1.20`` is :const:`2.50`.  The trailing zero is kept to indicate significance.
43   This is the customary presentation for monetary applications. For
44   multiplication, the "schoolbook" approach uses all the figures in the
45   multiplicands.  For instance, ``1.3 * 1.2`` gives :const:`1.56` while ``1.30 *
46   1.20`` gives :const:`1.5600`.
48 * Unlike hardware based binary floating point, the decimal module has a user
49   alterable precision (defaulting to 28 places) which can be as large as needed for
50   a given problem::
52      >>> getcontext().prec = 6
53      >>> Decimal(1) / Decimal(7)
54      Decimal('0.142857')
55      >>> getcontext().prec = 28
56      >>> Decimal(1) / Decimal(7)
57      Decimal('0.1428571428571428571428571429')
59 * Both binary and decimal floating point are implemented in terms of published
60   standards.  While the built-in float type exposes only a modest portion of its
61   capabilities, the decimal module exposes all required parts of the standard.
62   When needed, the programmer has full control over rounding and signal handling.
63   This includes an option to enforce exact arithmetic by using exceptions
64   to block any inexact operations.
66 * The decimal module was designed to support "without prejudice, both exact
67   unrounded decimal arithmetic (sometimes called fixed-point arithmetic)
68   and rounded floating-point arithmetic."  -- excerpt from the decimal
69   arithmetic specification.
71 The module design is centered around three concepts:  the decimal number, the
72 context for arithmetic, and signals.
74 A decimal number is immutable.  It has a sign, coefficient digits, and an
75 exponent.  To preserve significance, the coefficient digits do not truncate
76 trailing zeros.  Decimals also include special values such as
77 :const:`Infinity`, :const:`-Infinity`, and :const:`NaN`.  The standard also
78 differentiates :const:`-0` from :const:`+0`.
80 The context for arithmetic is an environment specifying precision, rounding
81 rules, limits on exponents, flags indicating the results of operations, and trap
82 enablers which determine whether signals are treated as exceptions.  Rounding
83 options include :const:`ROUND_CEILING`, :const:`ROUND_DOWN`,
84 :const:`ROUND_FLOOR`, :const:`ROUND_HALF_DOWN`, :const:`ROUND_HALF_EVEN`,
85 :const:`ROUND_HALF_UP`, :const:`ROUND_UP`, and :const:`ROUND_05UP`.
87 Signals are groups of exceptional conditions arising during the course of
88 computation.  Depending on the needs of the application, signals may be ignored,
89 considered as informational, or treated as exceptions. The signals in the
90 decimal module are: :const:`Clamped`, :const:`InvalidOperation`,
91 :const:`DivisionByZero`, :const:`Inexact`, :const:`Rounded`, :const:`Subnormal`,
92 :const:`Overflow`, and :const:`Underflow`.
94 For each signal there is a flag and a trap enabler.  When a signal is
95 encountered, its flag is incremented from zero and, then, if the trap enabler is
96 set to one, an exception is raised.  Flags are sticky, so the user needs to
97 reset them before monitoring a calculation.
100 .. seealso::
102    * IBM's General Decimal Arithmetic Specification, `The General Decimal Arithmetic
103      Specification <http://www2.hursley.ibm.com/decimal/decarith.html>`_.
105    * IEEE standard 854-1987, `Unofficial IEEE 854 Text
106      <http://754r.ucbtest.org/standards/854.pdf>`_.
108 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
111 .. _decimal-tutorial:
113 Quick-start Tutorial
114 --------------------
116 The usual start to using decimals is importing the module, viewing the current
117 context with :func:`getcontext` and, if necessary, setting new values for
118 precision, rounding, or enabled traps::
120    >>> from decimal import *
121    >>> getcontext()
122    Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
123            capitals=1, flags=[], traps=[Overflow, InvalidOperation,
124            DivisionByZero])
126    >>> getcontext().prec = 7       # Set a new precision
128 Decimal instances can be constructed from integers, strings, or tuples.  To
129 create a Decimal from a :class:`float`, first convert it to a string.  This
130 serves as an explicit reminder of the details of the conversion (including
131 representation error).  Decimal numbers include special values such as
132 :const:`NaN` which stands for "Not a number", positive and negative
133 :const:`Infinity`, and :const:`-0`.         ::
135    >>> Decimal(10)
136    Decimal('10')
137    >>> Decimal('3.14')
138    Decimal('3.14')
139    >>> Decimal((0, (3, 1, 4), -2))
140    Decimal('3.14')
141    >>> Decimal(str(2.0 ** 0.5))
142    Decimal('1.41421356237')
143    >>> Decimal(2) ** Decimal('0.5')
144    Decimal('1.414213562373095048801688724')
145    >>> Decimal('NaN')
146    Decimal('NaN')
147    >>> Decimal('-Infinity')
148    Decimal('-Infinity')
150 The significance of a new Decimal is determined solely by the number of digits
151 input.  Context precision and rounding only come into play during arithmetic
152 operations. ::
154    >>> getcontext().prec = 6
155    >>> Decimal('3.0')
156    Decimal('3.0')
157    >>> Decimal('3.1415926535')
158    Decimal('3.1415926535')
159    >>> Decimal('3.1415926535') + Decimal('2.7182818285')
160    Decimal('5.85987')
161    >>> getcontext().rounding = ROUND_UP
162    >>> Decimal('3.1415926535') + Decimal('2.7182818285')
163    Decimal('5.85988')
165 Decimals interact well with much of the rest of Python.  Here is a small decimal
166 floating point flying circus::
168    >>> data = map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split())
169    >>> max(data)
170    Decimal('9.25')
171    >>> min(data)
172    Decimal('0.03')
173    >>> sorted(data)
174    [Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
175     Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
176    >>> sum(data)
177    Decimal('19.29')
178    >>> a,b,c = data[:3]
179    >>> str(a)
180    '1.34'
181    >>> float(a)
182    1.3400000000000001
183    >>> round(a, 1)     # round() first converts to binary floating point
184    1.3
185    >>> int(a)
186    1
187    >>> a * 5
188    Decimal('6.70')
189    >>> a * b
190    Decimal('2.5058')
191    >>> c % a
192    Decimal('0.77')
194 And some mathematical functions are also available to Decimal::
196    >>> Decimal(2).sqrt()
197    Decimal('1.414213562373095048801688724')
198    >>> Decimal(1).exp()
199    Decimal('2.718281828459045235360287471')
200    >>> Decimal('10').ln()
201    Decimal('2.302585092994045684017991455')
202    >>> Decimal('10').log10()
203    Decimal('1')
205 The :meth:`quantize` method rounds a number to a fixed exponent.  This method is
206 useful for monetary applications that often round results to a fixed number of
207 places::
209    >>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
210    Decimal('7.32')
211    >>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
212    Decimal('8')
214 As shown above, the :func:`getcontext` function accesses the current context and
215 allows the settings to be changed.  This approach meets the needs of most
216 applications.
218 For more advanced work, it may be useful to create alternate contexts using the
219 Context() constructor.  To make an alternate active, use the :func:`setcontext`
220 function.
222 In accordance with the standard, the :mod:`Decimal` module provides two ready to
223 use standard contexts, :const:`BasicContext` and :const:`ExtendedContext`. The
224 former is especially useful for debugging because many of the traps are
225 enabled::
227    >>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
228    >>> setcontext(myothercontext)
229    >>> Decimal(1) / Decimal(7)
230    Decimal('0.142857142857142857142857142857142857142857142857142857142857')
232    >>> ExtendedContext
233    Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
234            capitals=1, flags=[], traps=[])
235    >>> setcontext(ExtendedContext)
236    >>> Decimal(1) / Decimal(7)
237    Decimal('0.142857143')
238    >>> Decimal(42) / Decimal(0)
239    Decimal('Infinity')
241    >>> setcontext(BasicContext)
242    >>> Decimal(42) / Decimal(0)
243    Traceback (most recent call last):
244      File "<pyshell#143>", line 1, in -toplevel-
245        Decimal(42) / Decimal(0)
246    DivisionByZero: x / 0
248 Contexts also have signal flags for monitoring exceptional conditions
249 encountered during computations.  The flags remain set until explicitly cleared,
250 so it is best to clear the flags before each set of monitored computations by
251 using the :meth:`clear_flags` method. ::
253    >>> setcontext(ExtendedContext)
254    >>> getcontext().clear_flags()
255    >>> Decimal(355) / Decimal(113)
256    Decimal('3.14159292')
257    >>> getcontext()
258    Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999999, Emax=999999999,
259            capitals=1, flags=[Inexact, Rounded], traps=[])
261 The *flags* entry shows that the rational approximation to :const:`Pi` was
262 rounded (digits beyond the context precision were thrown away) and that the
263 result is inexact (some of the discarded digits were non-zero).
265 Individual traps are set using the dictionary in the :attr:`traps` field of a
266 context::
268    >>> Decimal(1) / Decimal(0)
269    Decimal('Infinity')
270    >>> getcontext().traps[DivisionByZero] = 1
271    >>> Decimal(1) / Decimal(0)
272    Traceback (most recent call last):
273      File "<pyshell#112>", line 1, in -toplevel-
274        Decimal(1) / Decimal(0)
275    DivisionByZero: x / 0
277 Most programs adjust the current context only once, at the beginning of the
278 program.  And, in many applications, data is converted to :class:`Decimal` with
279 a single cast inside a loop.  With context set and decimals created, the bulk of
280 the program manipulates the data no differently than with other Python numeric
281 types.
283 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
286 .. _decimal-decimal:
288 Decimal objects
289 ---------------
292 .. class:: Decimal([value [, context]])
294    Construct a new :class:`Decimal` object based from *value*.
296    *value* can be an integer, string, tuple, or another :class:`Decimal`
297    object. If no *value* is given, returns ``Decimal('0')``.  If *value* is a
298    string, it should conform to the decimal numeric string syntax after leading
299    and trailing whitespace characters are removed::
301       sign           ::=  '+' | '-'
302       digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
303       indicator      ::=  'e' | 'E'
304       digits         ::=  digit [digit]...
305       decimal-part   ::=  digits '.' [digits] | ['.'] digits
306       exponent-part  ::=  indicator [sign] digits
307       infinity       ::=  'Infinity' | 'Inf'
308       nan            ::=  'NaN' [digits] | 'sNaN' [digits]
309       numeric-value  ::=  decimal-part [exponent-part] | infinity
310       numeric-string ::=  [sign] numeric-value | [sign] nan  
312    If *value* is a :class:`tuple`, it should have three components, a sign
313    (:const:`0` for positive or :const:`1` for negative), a :class:`tuple` of
314    digits, and an integer exponent. For example, ``Decimal((0, (1, 4, 1, 4), -3))``
315    returns ``Decimal('1.414')``.
317    The *context* precision does not affect how many digits are stored. That is
318    determined exclusively by the number of digits in *value*. For example,
319    ``Decimal('3.00000')`` records all five zeros even if the context precision is
320    only three.
322    The purpose of the *context* argument is determining what to do if *value* is a
323    malformed string.  If the context traps :const:`InvalidOperation`, an exception
324    is raised; otherwise, the constructor returns a new Decimal with the value of
325    :const:`NaN`.
327    Once constructed, :class:`Decimal` objects are immutable.
329    .. versionchanged:: 2.6
330       leading and trailing whitespace characters are permitted when
331       creating a Decimal instance from a string.
333 Decimal floating point objects share many properties with the other built-in
334 numeric types such as :class:`float` and :class:`int`.  All of the usual math
335 operations and special methods apply.  Likewise, decimal objects can be copied,
336 pickled, printed, used as dictionary keys, used as set elements, compared,
337 sorted, and coerced to another type (such as :class:`float` or :class:`long`).
339 In addition to the standard numeric properties, decimal floating point objects
340 also have a number of specialized methods:
343 .. method:: Decimal.adjusted()
345    Return the adjusted exponent after shifting out the coefficient's rightmost
346    digits until only the lead digit remains: ``Decimal('321e+5').adjusted()``
347    returns seven.  Used for determining the position of the most significant digit
348    with respect to the decimal point.
351 .. method:: Decimal.as_tuple()
353    Return a :term:`named tuple` representation of the number:
354    ``DecimalTuple(sign, digits, exponent)``.
356    .. versionchanged:: 2.6
357       Use a named tuple.
360 .. method:: Decimal.canonical()
362    Return the canonical encoding of the argument.  Currently, the
363    encoding of a :class:`Decimal` instance is always canonical, so
364    this operation returns its argument unchanged.
366    .. versionadded:: 2.6
368 .. method:: Decimal.compare(other[, context])
370    Compare the values of two Decimal instances.  This operation
371    behaves in the same way as the usual comparison method
372    :meth:`__cmp__`, except that :meth:`compare` returns a Decimal
373    instance rather than an integer, and if either operand is a NaN
374    then the result is a NaN::
376       a or b is a NaN ==> Decimal('NaN')
377       a < b           ==> Decimal('-1')
378       a == b          ==> Decimal('0')
379       a > b           ==> Decimal('1')
381 .. method:: Decimal.compare_signal(other[, context])
383    This operation is identical to the :meth:`compare` method, except
384    that all NaNs signal.  That is, if neither operand is a signaling
385    NaN then any quiet NaN operand is treated as though it were a
386    signaling NaN.
388    .. versionadded:: 2.6
390 .. method:: Decimal.compare_total(other)
392    Compare two operands using their abstract representation rather
393    than their numerical value.  Similar to the :meth:`compare` method,
394    but the result gives a total ordering on :class:`Decimal`
395    instances.  Two :class:`Decimal` instances with the same numeric
396    value but different representations compare unequal in this
397    ordering::
398    
399       >>> Decimal('12.0').compare_total(Decimal('12'))
400       Decimal('-1')
402    Quiet and signaling NaNs are also included in the total ordering.
403    The result of this function is ``Decimal('0')`` if both operands
404    have the same representation, ``Decimal('-1')`` if the first
405    operand is lower in the total order than the second, and
406    ``Decimal('1')`` if the first operand is higher in the total order
407    than the second operand.  See the specification for details of the
408    total order.
410    .. versionadded:: 2.6
412 .. method:: Decimal.compare_total_mag(other)
414    Compare two operands using their abstract representation rather
415    than their value as in :meth:`compare_total`, but ignoring the sign
416    of each operand.  ``x.compare_total_mag(y)`` is equivalent to
417    ``x.copy_abs().compare_total(y.copy_abs())``.
419    .. versionadded:: 2.6
421 .. method:: Decimal.copy_abs()
423    Return the absolute value of the argument.  This operation is
424    unaffected by the context and is quiet: no flags are changed and no
425    rounding is performed.
427    .. versionadded:: 2.6
429 .. method:: Decimal.copy_negate()
431    Return the negation of the argument.  This operation is unaffected
432    by the context and is quiet: no flags are changed and no rounding
433    is performed.
435    .. versionadded:: 2.6
437 .. method:: Decimal.copy_sign(other)
439    Return a copy of the first operand with the sign set to be the
440    same as the sign of the second operand.  For example::
442       >>> Decimal('2.3').copy_sign(Decimal('-1.5'))
443       Decimal('-2.3')
444    
445    This operation is unaffected by the context and is quiet: no flags
446    are changed and no rounding is performed.
448    .. versionadded:: 2.6
450 .. method:: Decimal.exp([context])
452    Return the value of the (natural) exponential function ``e**x`` at the
453    given number.  The result is correctly rounded using the
454    :const:`ROUND_HALF_EVEN` rounding mode.
456    >>> Decimal(1).exp()
457    Decimal('2.718281828459045235360287471')
458    >>> Decimal(321).exp()
459    Decimal('2.561702493119680037517373933E+139')
461    .. versionadded:: 2.6
463 .. method:: Decimal.fma(other, third[, context])
465    Fused multiply-add.  Return self*other+third with no rounding of
466    the intermediate product self*other.
468    >>> Decimal(2).fma(3, 5)
469    Decimal('11')
471    .. versionadded:: 2.6
473 .. method:: Decimal.is_canonical()
475    Return :const:`True` if the argument is canonical and
476    :const:`False` otherwise.  Currently, a :class:`Decimal` instance
477    is always canonical, so this operation always returns
478    :const:`True`.
480    .. versionadded:: 2.6
482 .. method:: is_finite()
484    Return :const:`True` if the argument is a finite number, and
485    :const:`False` if the argument is an infinity or a NaN.
487    .. versionadded:: 2.6
489 .. method:: is_infinite()
491    Return :const:`True` if the argument is either positive or
492    negative infinity and :const:`False` otherwise.
494    .. versionadded:: 2.6
496 .. method:: is_nan()
498    Return :const:`True` if the argument is a (quiet or signaling)
499    NaN and :const:`False` otherwise.
501    .. versionadded:: 2.6
503 .. method:: is_normal()
505    Return :const:`True` if the argument is a *normal* finite number.
506    Return :const:`False` if the argument is zero, subnormal, infinite
507    or a NaN.
509    .. versionadded:: 2.6
511 .. method:: is_qnan()
513    Return :const:`True` if the argument is a quiet NaN, and
514    :const:`False` otherwise.
516    .. versionadded:: 2.6
518 .. method:: is_signed()
520    Return :const:`True` if the argument has a negative sign and
521    :const:`False` otherwise.  Note that zeros and NaNs can both carry
522    signs.
524    .. versionadded:: 2.6
526 .. method:: is_snan()
528    Return :const:`True` if the argument is a signaling NaN and
529    :const:`False` otherwise.
531    .. versionadded:: 2.6
533 .. method:: is_subnormal()
535    Return :const:`True` if the argument is subnormal, and
536    :const:`False` otherwise.
538    .. versionadded:: 2.6
540 .. method:: is_zero()
542    Return :const:`True` if the argument is a (positive or negative)
543    zero and :const:`False` otherwise.
545    .. versionadded:: 2.6
547 .. method:: Decimal.ln([context])
549    Return the natural (base e) logarithm of the operand.  The result
550    is correctly rounded using the :const:`ROUND_HALF_EVEN` rounding
551    mode.
553    .. versionadded:: 2.6
555 .. method:: Decimal.log10([context])
557    Return the base ten logarithm of the operand.  The result is
558    correctly rounded using the :const:`ROUND_HALF_EVEN` rounding mode.
560    .. versionadded:: 2.6
562 .. method:: Decimal.logb([context])
564    For a nonzero number, return the adjusted exponent of its operand
565    as a :class:`Decimal` instance.  If the operand is a zero then
566    ``Decimal('-Infinity')`` is returned and the
567    :const:`DivisionByZero` flag is raised.  If the operand is an
568    infinity then ``Decimal('Infinity')`` is returned.
570    .. versionadded:: 2.6
572 .. method:: Decimal.logical_and(other[, context])
574    :meth:`logical_and` is a logical operation which takes two
575    *logical operands* (see :ref:`logical_operands_label`).  The result
576    is the digit-wise ``and`` of the two operands.
578    .. versionadded:: 2.6
580 .. method:: Decimal.logical_invert(other[, context])
582    :meth:`logical_invert` is a logical operation.  The argument must
583    be a *logical operand* (see :ref:`logical_operands_label`).  The
584    result is the digit-wise inversion of the operand.
586    .. versionadded:: 2.6
588 .. method:: Decimal.logical_or(other[, context])
590    :meth:`logical_or` is a logical operation which takes two *logical
591    operands* (see :ref:`logical_operands_label`).  The result is the
592    digit-wise ``or`` of the two operands.
594    .. versionadded:: 2.6
596 .. method:: Decimal.logical_xor(other[, context])
598    :meth:`logical_xor` is a logical operation which takes two
599    *logical operands* (see :ref:`logical_operands_label`).  The result
600    is the digit-wise exclusive or of the two operands.
602    .. versionadded:: 2.6
604 .. method:: Decimal.max(other[, context])
606    Like ``max(self, other)`` except that the context rounding rule is applied
607    before returning and that :const:`NaN` values are either signaled or ignored
608    (depending on the context and whether they are signaling or quiet).
610 .. method:: Decimal.max_mag(other[, context])
612    Similar to the :meth:`max` method, but the comparison is done using
613    the absolute values of the operands.
615    .. versionadded:: 2.6
617 .. method:: Decimal.min(other[, context])
619    Like ``min(self, other)`` except that the context rounding rule is applied
620    before returning and that :const:`NaN` values are either signaled or ignored
621    (depending on the context and whether they are signaling or quiet).
623 .. method:: Decimal.min_mag(other[, context])
625    Similar to the :meth:`min` method, but the comparison is done using
626    the absolute values of the operands.
628    .. versionadded:: 2.6
630 .. method:: Decimal.next_minus([context])
632    Return the largest number representable in the given context (or
633    in the current thread's context if no context is given) that is smaller
634    than the given operand.
636    .. versionadded:: 2.6
638 .. method:: Decimal.next_plus([context])
640    Return the smallest number representable in the given context (or
641    in the current thread's context if no context is given) that is
642    larger than the given operand.
644    .. versionadded:: 2.6
646 .. method:: Decimal.next_toward(other[, context])
648    If the two operands are unequal, return the number closest to the
649    first operand in the direction of the second operand.  If both
650    operands are numerically equal, return a copy of the first operand
651    with the sign set to be the same as the sign of the second operand.
653    .. versionadded:: 2.6
655 .. method:: Decimal.normalize([context])
657    Normalize the number by stripping the rightmost trailing zeros and converting
658    any result equal to :const:`Decimal('0')` to :const:`Decimal('0e0')`. Used for
659    producing canonical values for members of an equivalence class. For example,
660    ``Decimal('32.100')`` and ``Decimal('0.321000e+2')`` both normalize to the
661    equivalent value ``Decimal('32.1')``.
663 .. method:: Decimal.number_class([context])
665    Return a string describing the *class* of the operand.  The
666    returned value is one of the following ten strings.
668    * ``"-Infinity"``, indicating that the operand is negative infinity.
669    * ``"-Normal"``, indicating that the operand is a negative normal number.
670    * ``"-Subnormal"``, indicating that the operand is negative and subnormal.
671    * ``"-Zero"``, indicating that the operand is a negative zero.
672    * ``"+Zero"``, indicating that the operand is a positive zero.
673    * ``"+Subnormal"``, indicating that the operand is positive and subnormal.
674    * ``"+Normal"``, indicating that the operand is a positive normal number.
675    * ``"+Infinity"``, indicating that the operand is positive infinity.
676    * ``"NaN"``, indicating that the operand is a quiet NaN (Not a Number).
677    * ``"sNaN"``, indicating that the operand is a signaling NaN.
679    .. versionadded:: 2.6
681 .. method:: Decimal.quantize(exp[, rounding[, context[, watchexp]]])
683    Return a value equal to the first operand after rounding and
684    having the exponent of the second operand.
686    >>> Decimal('1.41421356').quantize(Decimal('1.000'))
687    Decimal('1.414')
689    Unlike other operations, if the length of the coefficient after the
690    quantize operation would be greater than precision, then an
691    :const:`InvalidOperation` is signaled. This guarantees that, unless
692    there is an error condition, the quantized exponent is always equal
693    to that of the right-hand operand.
695    Also unlike other operations, quantize never signals Underflow,
696    even if the result is subnormal and inexact.
698    If the exponent of the second operand is larger than that of the
699    first then rounding may be necessary.  In this case, the rounding
700    mode is determined by the ``rounding`` argument if given, else by
701    the given ``context`` argument; if neither argument is given the
702    rounding mode of the current thread's context is used.
704    If *watchexp* is set (default), then an error is returned whenever the
705    resulting exponent is greater than :attr:`Emax` or less than :attr:`Etiny`.
707 .. method:: Decimal.radix()
709    Return ``Decimal(10)``, the radix (base) in which the
710    :class:`Decimal` class does all its arithmetic.  Included for
711    compatibility with the specification.
713    .. versionadded:: 2.6
715 .. method:: Decimal.remainder_near(other[, context])
717    Compute the modulo as either a positive or negative value depending on which is
718    closest to zero.  For instance, ``Decimal(10).remainder_near(6)`` returns
719    ``Decimal('-2')`` which is closer to zero than ``Decimal('4')``.
721    If both are equally close, the one chosen will have the same sign as *self*.
723 .. method:: Decimal.rotate(other[, context])
725    Return the result of rotating the digits of the first operand by
726    an amount specified by the second operand.  The second operand
727    must be an integer in the range -precision through precision.  The
728    absolute value of the second operand gives the number of places to
729    rotate.  If the second operand is positive then rotation is to the
730    left; otherwise rotation is to the right.  The coefficient of the
731    first operand is padded on the left with zeros to length precision
732    if necessary.  The sign and exponent of the first operand are
733    unchanged.
735    .. versionadded:: 2.6
737 .. method:: Decimal.same_quantum(other[, context])
739    Test whether self and other have the same exponent or whether both are
740    :const:`NaN`.
742 .. method:: Decimal.scaleb(other[, context])
744    Return the first operand with exponent adjusted by the second.
745    Equivalently, return the first operand multiplied by ``10**other``.
746    The second operand must be an integer.
748    .. versionadded:: 2.6
750 .. method:: Decimal.shift(other[, context])
752    Return the result of shifting the digits of the first operand by
753    an amount specified by the second operand.  The second operand must
754    be an integer in the range -precision through precision.  The
755    absolute value of the second operand gives the number of places to
756    shift.  If the second operand is positive then the shift is to the
757    left; otherwise the shift is to the right.  Digits shifted into the
758    coefficient are zeros.  The sign and exponent of the first operand
759    are unchanged.
761    .. versionadded:: 2.6
763 .. method:: Decimal.sqrt([context])
765    Return the square root of the argument to full precision.
768 .. method:: Decimal.to_eng_string([context])
770    Convert to an engineering-type string.
772    Engineering notation has an exponent which is a multiple of 3, so there are up
773    to 3 digits left of the decimal place.  For example, converts
774    ``Decimal('123E+1')`` to ``Decimal('1.23E+3')``
776 .. method:: Decimal.to_integral([rounding[, context]])
778    Identical to the :meth:`to_integral_value` method.  The ``to_integral``
779    name has been kept for compatibility with older versions.
781 .. method:: Decimal.to_integral_exact([rounding[, context]])
783    Round to the nearest integer, signaling
784    :const:`Inexact` or :const:`Rounded` as appropriate if rounding
785    occurs.  The rounding mode is determined by the ``rounding``
786    parameter if given, else by the given ``context``.  If neither
787    parameter is given then the rounding mode of the current context is
788    used.
790    .. versionadded:: 2.6
792 .. method:: Decimal.to_integral_value([rounding[, context]])
794    Round to the nearest integer without signaling :const:`Inexact` or
795    :const:`Rounded`.  If given, applies *rounding*; otherwise, uses the rounding
796    method in either the supplied *context* or the current context.
798    .. versionchanged:: 2.6
799       renamed from ``to_integral`` to ``to_integral_value``.  The old name
800       remains valid for compatibility.
802 .. method:: Decimal.trim()
804    Return the decimal with *insignificant* trailing zeros removed.
805    Here, a trailing zero is considered insignificant either if it
806    follows the decimal point, or if the exponent of the argument (that
807    is, the last element of the :meth:`as_tuple` representation) is
808    positive.
810    .. versionadded:: 2.6
812 .. _logical_operands_label:
814 Logical operands
815 ^^^^^^^^^^^^^^^^
817 The :meth:`logical_and`, :meth:`logical_invert`, :meth:`logical_or`,
818 and :meth:`logical_xor` methods expect their arguments to be *logical
819 operands*.  A *logical operand* is a :class:`Decimal` instance whose
820 exponent and sign are both zero, and whose digits are all either
821 :const:`0` or :const:`1`.
823 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
826 .. _decimal-context:
828 Context objects
829 ---------------
831 Contexts are environments for arithmetic operations.  They govern precision, set
832 rules for rounding, determine which signals are treated as exceptions, and limit
833 the range for exponents.
835 Each thread has its own current context which is accessed or changed using the
836 :func:`getcontext` and :func:`setcontext` functions:
839 .. function:: getcontext()
841    Return the current context for the active thread.
844 .. function:: setcontext(c)
846    Set the current context for the active thread to *c*.
848 Beginning with Python 2.5, you can also use the :keyword:`with` statement and
849 the :func:`localcontext` function to temporarily change the active context.
852 .. function:: localcontext([c])
854    Return a context manager that will set the current context for the active thread
855    to a copy of *c* on entry to the with-statement and restore the previous context
856    when exiting the with-statement. If no context is specified, a copy of the
857    current context is used.
859    .. versionadded:: 2.5
861    For example, the following code sets the current decimal precision to 42 places,
862    performs a calculation, and then automatically restores the previous context::
864       from decimal import localcontext
866       with localcontext() as ctx:
867           ctx.prec = 42   # Perform a high precision calculation
868           s = calculate_something()
869       s = +s  # Round the final result back to the default precision
871 New contexts can also be created using the :class:`Context` constructor
872 described below. In addition, the module provides three pre-made contexts:
875 .. class:: BasicContext
877    This is a standard context defined by the General Decimal Arithmetic
878    Specification.  Precision is set to nine.  Rounding is set to
879    :const:`ROUND_HALF_UP`.  All flags are cleared.  All traps are enabled (treated
880    as exceptions) except :const:`Inexact`, :const:`Rounded`, and
881    :const:`Subnormal`.
883    Because many of the traps are enabled, this context is useful for debugging.
886 .. class:: ExtendedContext
888    This is a standard context defined by the General Decimal Arithmetic
889    Specification.  Precision is set to nine.  Rounding is set to
890    :const:`ROUND_HALF_EVEN`.  All flags are cleared.  No traps are enabled (so that
891    exceptions are not raised during computations).
893    Because the traps are disabled, this context is useful for applications that
894    prefer to have result value of :const:`NaN` or :const:`Infinity` instead of
895    raising exceptions.  This allows an application to complete a run in the
896    presence of conditions that would otherwise halt the program.
899 .. class:: DefaultContext
901    This context is used by the :class:`Context` constructor as a prototype for new
902    contexts.  Changing a field (such a precision) has the effect of changing the
903    default for new contexts creating by the :class:`Context` constructor.
905    This context is most useful in multi-threaded environments.  Changing one of the
906    fields before threads are started has the effect of setting system-wide
907    defaults.  Changing the fields after threads have started is not recommended as
908    it would require thread synchronization to prevent race conditions.
910    In single threaded environments, it is preferable to not use this context at
911    all.  Instead, simply create contexts explicitly as described below.
913    The default values are precision=28, rounding=ROUND_HALF_EVEN, and enabled traps
914    for Overflow, InvalidOperation, and DivisionByZero.
916 In addition to the three supplied contexts, new contexts can be created with the
917 :class:`Context` constructor.
920 .. class:: Context(prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
922    Creates a new context.  If a field is not specified or is :const:`None`, the
923    default values are copied from the :const:`DefaultContext`.  If the *flags*
924    field is not specified or is :const:`None`, all flags are cleared.
926    The *prec* field is a positive integer that sets the precision for arithmetic
927    operations in the context.
929    The *rounding* option is one of:
931    * :const:`ROUND_CEILING` (towards :const:`Infinity`),
932    * :const:`ROUND_DOWN` (towards zero),
933    * :const:`ROUND_FLOOR` (towards :const:`-Infinity`),
934    * :const:`ROUND_HALF_DOWN` (to nearest with ties going towards zero),
935    * :const:`ROUND_HALF_EVEN` (to nearest with ties going to nearest even integer),
936    * :const:`ROUND_HALF_UP` (to nearest with ties going away from zero), or
937    * :const:`ROUND_UP` (away from zero).
938    * :const:`ROUND_05UP` (away from zero if last digit after rounding towards zero 
939      would have been 0 or 5; otherwise towards zero)
941    The *traps* and *flags* fields list any signals to be set. Generally, new
942    contexts should only set traps and leave the flags clear.
944    The *Emin* and *Emax* fields are integers specifying the outer limits allowable
945    for exponents.
947    The *capitals* field is either :const:`0` or :const:`1` (the default). If set to
948    :const:`1`, exponents are printed with a capital :const:`E`; otherwise, a
949    lowercase :const:`e` is used: :const:`Decimal('6.02e+23')`.
951    .. versionchanged:: 2.6
952       The :const:`ROUND_05UP` rounding mode was added.
954 The :class:`Context` class defines several general purpose methods as
955 well as a large number of methods for doing arithmetic directly in a
956 given context.  In addition, for each of the :class:`Decimal` methods
957 described above (with the exception of the :meth:`adjusted` and
958 :meth:`as_tuple` methods) there is a corresponding :class:`Context`
959 method.  For example, ``C.exp(x)`` is equivalent to
960 ``x.exp(context=C)``.
962 .. method:: Context.clear_flags()
964    Resets all of the flags to :const:`0`.
967 .. method:: Context.copy()
969    Return a duplicate of the context.
971 .. method:: Context.copy_decimal(num)
973    Return a copy of the Decimal instance num.
975 .. method:: Context.create_decimal(num)
977    Creates a new Decimal instance from *num* but using *self* as context. Unlike
978    the :class:`Decimal` constructor, the context precision, rounding method, flags,
979    and traps are applied to the conversion.
981    This is useful because constants are often given to a greater precision than is
982    needed by the application.  Another benefit is that rounding immediately
983    eliminates unintended effects from digits beyond the current precision. In the
984    following example, using unrounded inputs means that adding zero to a sum can
985    change the result::
987       >>> getcontext().prec = 3
988       >>> Decimal('3.4445') + Decimal('1.0023')
989       Decimal('4.45')
990       >>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
991       Decimal('4.44')
993    This method implements the to-number operation of the IBM
994    specification.  If the argument is a string, no leading or trailing
995    whitespace is permitted.
997 .. method:: Context.Etiny()
999    Returns a value equal to ``Emin - prec + 1`` which is the minimum exponent value
1000    for subnormal results.  When underflow occurs, the exponent is set to
1001    :const:`Etiny`.
1004 .. method:: Context.Etop()
1006    Returns a value equal to ``Emax - prec + 1``.
1008 The usual approach to working with decimals is to create :class:`Decimal`
1009 instances and then apply arithmetic operations which take place within the
1010 current context for the active thread.  An alternative approach is to use context
1011 methods for calculating within a specific context.  The methods are similar to
1012 those for the :class:`Decimal` class and are only briefly recounted here.
1015 .. method:: Context.abs(x)
1017    Returns the absolute value of *x*.
1020 .. method:: Context.add(x, y)
1022    Return the sum of *x* and *y*.
1025 .. method:: Context.divide(x, y)
1027    Return *x* divided by *y*.
1030 .. method:: Context.divide_int(x, y)
1032    Return *x* divided by *y*, truncated to an integer.
1035 .. method:: Context.divmod(x, y)
1037    Divides two numbers and returns the integer part of the result.
1040 .. method:: Context.minus(x)
1042    Minus corresponds to the unary prefix minus operator in Python.
1045 .. method:: Context.multiply(x, y)
1047    Return the product of *x* and *y*.
1050 .. method:: Context.plus(x)
1052    Plus corresponds to the unary prefix plus operator in Python.  This operation
1053    applies the context precision and rounding, so it is *not* an identity
1054    operation.
1057 .. method:: Context.power(x, y[, modulo])
1059    Return ``x`` to the power of ``y``, reduced modulo ``modulo`` if
1060    given.
1062    With two arguments, compute ``x**y``.  If ``x`` is negative then
1063    ``y`` must be integral.  The result will be inexact unless ``y`` is
1064    integral and the result is finite and can be expressed exactly in
1065    'precision' digits.  The result should always be correctly rounded,
1066    using the rounding mode of the current thread's context.
1068    With three arguments, compute ``(x**y) % modulo``.  For the three
1069    argument form, the following restrictions on the arguments hold:
1071       - all three arguments must be integral
1072       - ``y`` must be nonnegative
1073       - at least one of ``x`` or ``y`` must be nonzero
1074       - ``modulo`` must be nonzero and have at most 'precision' digits
1076    The result of ``Context.power(x, y, modulo)`` is identical to
1077    the result that would be obtained by computing ``(x**y) %
1078    modulo`` with unbounded precision, but is computed more
1079    efficiently.  It is always exact.
1081    .. versionchanged:: 2.6 
1082       ``y`` may now be nonintegral in ``x**y``.
1083       Stricter requirements for the three-argument version.
1086 .. method:: Context.remainder(x, y)
1088    Returns the remainder from integer division.
1090    The sign of the result, if non-zero, is the same as that of the original
1091    dividend.
1093 .. method:: Context.subtract(x, y)
1095    Return the difference between *x* and *y*.
1097 .. method:: Context.to_sci_string(x)
1099    Converts a number to a string using scientific notation.
1101 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1104 .. _decimal-signals:
1106 Signals
1107 -------
1109 Signals represent conditions that arise during computation. Each corresponds to
1110 one context flag and one context trap enabler.
1112 The context flag is incremented whenever the condition is encountered. After the
1113 computation, flags may be checked for informational purposes (for instance, to
1114 determine whether a computation was exact). After checking the flags, be sure to
1115 clear all flags before starting the next computation.
1117 If the context's trap enabler is set for the signal, then the condition causes a
1118 Python exception to be raised.  For example, if the :class:`DivisionByZero` trap
1119 is set, then a :exc:`DivisionByZero` exception is raised upon encountering the
1120 condition.
1123 .. class:: Clamped
1125    Altered an exponent to fit representation constraints.
1127    Typically, clamping occurs when an exponent falls outside the context's
1128    :attr:`Emin` and :attr:`Emax` limits.  If possible, the exponent is reduced to
1129    fit by adding zeros to the coefficient.
1132 .. class:: DecimalException
1134    Base class for other signals and a subclass of :exc:`ArithmeticError`.
1137 .. class:: DivisionByZero
1139    Signals the division of a non-infinite number by zero.
1141    Can occur with division, modulo division, or when raising a number to a negative
1142    power.  If this signal is not trapped, returns :const:`Infinity` or
1143    :const:`-Infinity` with the sign determined by the inputs to the calculation.
1146 .. class:: Inexact
1148    Indicates that rounding occurred and the result is not exact.
1150    Signals when non-zero digits were discarded during rounding. The rounded result
1151    is returned.  The signal flag or trap is used to detect when results are
1152    inexact.
1155 .. class:: InvalidOperation
1157    An invalid operation was performed.
1159    Indicates that an operation was requested that does not make sense. If not
1160    trapped, returns :const:`NaN`.  Possible causes include::
1162       Infinity - Infinity
1163       0 * Infinity
1164       Infinity / Infinity
1165       x % 0
1166       Infinity % x
1167       x._rescale( non-integer )
1168       sqrt(-x) and x > 0
1169       0 ** 0
1170       x ** (non-integer)
1171       x ** Infinity      
1174 .. class:: Overflow
1176    Numerical overflow.
1178    Indicates the exponent is larger than :attr:`Emax` after rounding has occurred.
1179    If not trapped, the result depends on the rounding mode, either pulling inward
1180    to the largest representable finite number or rounding outward to
1181    :const:`Infinity`.  In either case, :class:`Inexact` and :class:`Rounded` are
1182    also signaled.
1185 .. class:: Rounded
1187    Rounding occurred though possibly no information was lost.
1189    Signaled whenever rounding discards digits; even if those digits are zero (such
1190    as rounding :const:`5.00` to :const:`5.0`).   If not trapped, returns the result
1191    unchanged.  This signal is used to detect loss of significant digits.
1194 .. class:: Subnormal
1196    Exponent was lower than :attr:`Emin` prior to rounding.
1198    Occurs when an operation result is subnormal (the exponent is too small). If not
1199    trapped, returns the result unchanged.
1202 .. class:: Underflow
1204    Numerical underflow with result rounded to zero.
1206    Occurs when a subnormal result is pushed to zero by rounding. :class:`Inexact`
1207    and :class:`Subnormal` are also signaled.
1209 The following table summarizes the hierarchy of signals::
1211    exceptions.ArithmeticError(exceptions.StandardError)
1212        DecimalException
1213            Clamped
1214            DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
1215            Inexact
1216                Overflow(Inexact, Rounded)
1217                Underflow(Inexact, Rounded, Subnormal)
1218            InvalidOperation
1219            Rounded
1220            Subnormal
1222 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1225 .. _decimal-notes:
1227 Floating Point Notes
1228 --------------------
1231 Mitigating round-off error with increased precision
1232 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1234 The use of decimal floating point eliminates decimal representation error
1235 (making it possible to represent :const:`0.1` exactly); however, some operations
1236 can still incur round-off error when non-zero digits exceed the fixed precision.
1238 The effects of round-off error can be amplified by the addition or subtraction
1239 of nearly offsetting quantities resulting in loss of significance.  Knuth
1240 provides two instructive examples where rounded floating point arithmetic with
1241 insufficient precision causes the breakdown of the associative and distributive
1242 properties of addition::
1244    # Examples from Seminumerical Algorithms, Section 4.2.2.
1245    >>> from decimal import Decimal, getcontext
1246    >>> getcontext().prec = 8
1248    >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1249    >>> (u + v) + w
1250    Decimal('9.5111111')
1251    >>> u + (v + w)
1252    Decimal('10')
1254    >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1255    >>> (u*v) + (u*w)
1256    Decimal('0.01')
1257    >>> u * (v+w)
1258    Decimal('0.0060000')
1260 The :mod:`decimal` module makes it possible to restore the identities by
1261 expanding the precision sufficiently to avoid loss of significance::
1263    >>> getcontext().prec = 20
1264    >>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
1265    >>> (u + v) + w
1266    Decimal('9.51111111')
1267    >>> u + (v + w)
1268    Decimal('9.51111111')
1269    >>> 
1270    >>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
1271    >>> (u*v) + (u*w)
1272    Decimal('0.0060000')
1273    >>> u * (v+w)
1274    Decimal('0.0060000')
1277 Special values
1278 ^^^^^^^^^^^^^^
1280 The number system for the :mod:`decimal` module provides special values
1281 including :const:`NaN`, :const:`sNaN`, :const:`-Infinity`, :const:`Infinity`,
1282 and two zeros, :const:`+0` and :const:`-0`.
1284 Infinities can be constructed directly with:  ``Decimal('Infinity')``. Also,
1285 they can arise from dividing by zero when the :exc:`DivisionByZero` signal is
1286 not trapped.  Likewise, when the :exc:`Overflow` signal is not trapped, infinity
1287 can result from rounding beyond the limits of the largest representable number.
1289 The infinities are signed (affine) and can be used in arithmetic operations
1290 where they get treated as very large, indeterminate numbers.  For instance,
1291 adding a constant to infinity gives another infinite result.
1293 Some operations are indeterminate and return :const:`NaN`, or if the
1294 :exc:`InvalidOperation` signal is trapped, raise an exception.  For example,
1295 ``0/0`` returns :const:`NaN` which means "not a number".  This variety of
1296 :const:`NaN` is quiet and, once created, will flow through other computations
1297 always resulting in another :const:`NaN`.  This behavior can be useful for a
1298 series of computations that occasionally have missing inputs --- it allows the
1299 calculation to proceed while flagging specific results as invalid.
1301 A variant is :const:`sNaN` which signals rather than remaining quiet after every
1302 operation.  This is a useful return value when an invalid result needs to
1303 interrupt a calculation for special handling.
1305 The behavior of Python's comparison operators can be a little surprising where a
1306 :const:`NaN` is involved.  A test for equality where one of the operands is a
1307 quiet or signaling :const:`NaN` always returns :const:`False` (even when doing
1308 ``Decimal('NaN')==Decimal('NaN')``), while a test for inequality always returns
1309 :const:`True`.  An attempt to compare two Decimals using any of the ``<``,
1310 ``<=``, ``>`` or ``>=`` operators will raise the :exc:`InvalidOperation` signal
1311 if either operand is a :const:`NaN`, and return :const:`False` if this signal is
1312 not trapped.  Note that the General Decimal Arithmetic specification does not
1313 specify the behavior of direct comparisons; these rules for comparisons
1314 involving a :const:`NaN` were taken from the IEEE 854 standard (see Table 3 in
1315 section 5.7).  To ensure strict standards-compliance, use the :meth:`compare`
1316 and :meth:`compare-signal` methods instead.
1318 The signed zeros can result from calculations that underflow. They keep the sign
1319 that would have resulted if the calculation had been carried out to greater
1320 precision.  Since their magnitude is zero, both positive and negative zeros are
1321 treated as equal and their sign is informational.
1323 In addition to the two signed zeros which are distinct yet equal, there are
1324 various representations of zero with differing precisions yet equivalent in
1325 value.  This takes a bit of getting used to.  For an eye accustomed to
1326 normalized floating point representations, it is not immediately obvious that
1327 the following calculation returns a value equal to zero::
1329    >>> 1 / Decimal('Infinity')
1330    Decimal('0E-1000000026')
1332 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1335 .. _decimal-threads:
1337 Working with threads
1338 --------------------
1340 The :func:`getcontext` function accesses a different :class:`Context` object for
1341 each thread.  Having separate thread contexts means that threads may make
1342 changes (such as ``getcontext.prec=10``) without interfering with other threads.
1344 Likewise, the :func:`setcontext` function automatically assigns its target to
1345 the current thread.
1347 If :func:`setcontext` has not been called before :func:`getcontext`, then
1348 :func:`getcontext` will automatically create a new context for use in the
1349 current thread.
1351 The new context is copied from a prototype context called *DefaultContext*. To
1352 control the defaults so that each thread will use the same values throughout the
1353 application, directly modify the *DefaultContext* object. This should be done
1354 *before* any threads are started so that there won't be a race condition between
1355 threads calling :func:`getcontext`. For example::
1357    # Set applicationwide defaults for all threads about to be launched
1358    DefaultContext.prec = 12
1359    DefaultContext.rounding = ROUND_DOWN
1360    DefaultContext.traps = ExtendedContext.traps.copy()
1361    DefaultContext.traps[InvalidOperation] = 1
1362    setcontext(DefaultContext)
1364    # Afterwards, the threads can be started
1365    t1.start()
1366    t2.start()
1367    t3.start()
1368     . . .
1370 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1373 .. _decimal-recipes:
1375 Recipes
1376 -------
1378 Here are a few recipes that serve as utility functions and that demonstrate ways
1379 to work with the :class:`Decimal` class::
1381    def moneyfmt(value, places=2, curr='', sep=',', dp='.',
1382                 pos='', neg='-', trailneg=''):
1383        """Convert Decimal to a money formatted string.
1385        places:  required number of places after the decimal point
1386        curr:    optional currency symbol before the sign (may be blank)
1387        sep:     optional grouping separator (comma, period, space, or blank)
1388        dp:      decimal point indicator (comma or period)
1389                 only specify as blank when places is zero
1390        pos:     optional sign for positive numbers: '+', space or blank
1391        neg:     optional sign for negative numbers: '-', '(', space or blank
1392        trailneg:optional trailing minus indicator:  '-', ')', space or blank
1394        >>> d = Decimal('-1234567.8901')
1395        >>> moneyfmt(d, curr='$')
1396        '-$1,234,567.89'
1397        >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
1398        '1.234.568-'
1399        >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
1400        '($1,234,567.89)'
1401        >>> moneyfmt(Decimal(123456789), sep=' ')
1402        '123 456 789.00'
1403        >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
1404        '<.02>'
1406        """
1407        q = Decimal(10) ** -places      # 2 places --> '0.01'
1408        sign, digits, exp = value.quantize(q).as_tuple()  
1409        result = []
1410        digits = map(str, digits)
1411        build, next = result.append, digits.pop
1412        if sign:
1413            build(trailneg)
1414        for i in range(places):
1415            build(next() if digits else '0')
1416        build(dp)
1417        i = 0
1418        while digits:
1419            build(next())
1420            i += 1
1421            if i == 3 and digits:
1422                i = 0
1423                build(sep)
1424        build(curr)
1425        build(neg if sign else pos)
1426        return ''.join(reversed(result))
1428    def pi():
1429        """Compute Pi to the current precision.
1431        >>> print pi()
1432        3.141592653589793238462643383
1434        """
1435        getcontext().prec += 2  # extra digits for intermediate steps
1436        three = Decimal(3)      # substitute "three=3.0" for regular floats
1437        lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
1438        while s != lasts:
1439            lasts = s
1440            n, na = n+na, na+8
1441            d, da = d+da, da+32
1442            t = (t * n) / d
1443            s += t
1444        getcontext().prec -= 2
1445        return +s               # unary plus applies the new precision
1447    def exp(x):
1448        """Return e raised to the power of x.  Result type matches input type.
1450        >>> print exp(Decimal(1))
1451        2.718281828459045235360287471
1452        >>> print exp(Decimal(2))
1453        7.389056098930650227230427461
1454        >>> print exp(2.0)
1455        7.38905609893
1456        >>> print exp(2+0j)
1457        (7.38905609893+0j)
1459        """
1460        getcontext().prec += 2
1461        i, lasts, s, fact, num = 0, 0, 1, 1, 1
1462        while s != lasts:
1463            lasts = s    
1464            i += 1
1465            fact *= i
1466            num *= x     
1467            s += num / fact   
1468        getcontext().prec -= 2        
1469        return +s
1471    def cos(x):
1472        """Return the cosine of x as measured in radians.
1474        >>> print cos(Decimal('0.5'))
1475        0.8775825618903727161162815826
1476        >>> print cos(0.5)
1477        0.87758256189
1478        >>> print cos(0.5+0j)
1479        (0.87758256189+0j)
1481        """
1482        getcontext().prec += 2
1483        i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
1484        while s != lasts:
1485            lasts = s    
1486            i += 2
1487            fact *= i * (i-1)
1488            num *= x * x
1489            sign *= -1
1490            s += num / fact * sign 
1491        getcontext().prec -= 2        
1492        return +s
1494    def sin(x):
1495        """Return the sine of x as measured in radians.
1497        >>> print sin(Decimal('0.5'))
1498        0.4794255386042030002732879352
1499        >>> print sin(0.5)
1500        0.479425538604
1501        >>> print sin(0.5+0j)
1502        (0.479425538604+0j)
1504        """
1505        getcontext().prec += 2
1506        i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
1507        while s != lasts:
1508            lasts = s    
1509            i += 2
1510            fact *= i * (i-1)
1511            num *= x * x
1512            sign *= -1
1513            s += num / fact * sign 
1514        getcontext().prec -= 2        
1515        return +s
1518 .. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
1521 .. _decimal-faq:
1523 Decimal FAQ
1524 -----------
1526 Q. It is cumbersome to type ``decimal.Decimal('1234.5')``.  Is there a way to
1527 minimize typing when using the interactive interpreter?
1529 A. Some users abbreviate the constructor to just a single letter::
1531    >>> D = decimal.Decimal
1532    >>> D('1.23') + D('3.45')
1533    Decimal('4.68')
1535 Q. In a fixed-point application with two decimal places, some inputs have many
1536 places and need to be rounded.  Others are not supposed to have excess digits
1537 and need to be validated.  What methods should be used?
1539 A. The :meth:`quantize` method rounds to a fixed number of decimal places. If
1540 the :const:`Inexact` trap is set, it is also useful for validation::
1542    >>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
1544    >>> # Round to two places
1545    >>> Decimal('3.214').quantize(TWOPLACES)
1546    Decimal('3.21')
1548    >>> # Validate that a number does not exceed two places 
1549    >>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1550    Decimal('3.21')
1552    >>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
1553    Traceback (most recent call last):
1554       ...
1555    Inexact: Changed in rounding
1557 Q. Once I have valid two place inputs, how do I maintain that invariant
1558 throughout an application?
1560 A. Some operations like addition, subtraction, and multiplication by an integer
1561 will automatically preserve fixed point.  Others operations, like division and
1562 non-integer multiplication, will change the number of decimal places and need to
1563 be followed-up with a :meth:`quantize` step::
1565     >>> a = Decimal('102.72')           # Initial fixed-point values
1566     >>> b = Decimal('3.17')
1567     >>> a + b                           # Addition preserves fixed-point
1568     Decimal('105.89')
1569     >>> a - b
1570     Decimal('99.55')
1571     >>> a * 42                          # So does integer multiplication
1572     Decimal('4314.24')
1573     >>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
1574     Decimal('325.62')
1575     >>> (b / a).quantize(TWOPLACES)     # And quantize division
1576     Decimal('0.03')
1578 In developing fixed-point applications, it is convenient to define functions
1579 to handle the :meth:`quantize` step::
1581     >>> def mul(x, y, fp=TWOPLACES):
1582     ...     return (x * y).quantize(fp)
1583     >>> def div(x, y, fp=TWOPLACES):
1584     ...     return (x / y).quantize(fp)
1586     >>> mul(a, b)                       # Automatically preserve fixed-point
1587     Decimal('325.62')
1588     >>> div(b, a)
1589     Decimal('0.03')
1591 Q. There are many ways to express the same value.  The numbers :const:`200`,
1592 :const:`200.000`, :const:`2E2`, and :const:`.02E+4` all have the same value at
1593 various precisions. Is there a way to transform them to a single recognizable
1594 canonical value?
1596 A. The :meth:`normalize` method maps all equivalent values to a single
1597 representative::
1599    >>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
1600    >>> [v.normalize() for v in values]
1601    [Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]
1603 Q. Some decimal values always print with exponential notation.  Is there a way
1604 to get a non-exponential representation?
1606 A. For some values, exponential notation is the only way to express the number
1607 of significant places in the coefficient.  For example, expressing
1608 :const:`5.0E+3` as :const:`5000` keeps the value constant but cannot show the
1609 original's two-place significance.
1611 If an application does not care about tracking significance, it is easy to
1612 remove the exponent and trailing zeroes, losing significance, but keeping the
1613 value unchanged::
1615     >>> def remove_exponent(d):
1616     ...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
1618     >>> remove_exponent(Decimal('5E+3'))
1619     Decimal('5000')
1621 Q. Is there a way to convert a regular float to a :class:`Decimal`?
1623 A. Yes, all binary floating point numbers can be exactly expressed as a
1624 Decimal.  An exact conversion may take more precision than intuition would
1625 suggest, so we trap :const:`Inexact` to signal a need for more precision::
1627     def float_to_decimal(f):
1628         "Convert a floating point number to a Decimal with no loss of information"
1629         n, d = f.as_integer_ratio()
1630         with localcontext() as ctx:
1631             ctx.traps[Inexact] = True
1632             while True:
1633                 try:
1634                    return Decimal(n) / Decimal(d)
1635                 except Inexact:
1636                     ctx.prec += 1
1638     >>> float_to_decimal(math.pi)
1639     Decimal('3.141592653589793115997963468544185161590576171875')
1641 Q. Why isn't the :func:`float_to_decimal` routine included in the module?
1643 A. There is some question about whether it is advisable to mix binary and
1644 decimal floating point.  Also, its use requires some care to avoid the
1645 representation issues associated with binary floating point::
1647    >>> float_to_decimal(1.1)
1648    Decimal('1.100000000000000088817841970012523233890533447265625')
1650 Q. Within a complex calculation, how can I make sure that I haven't gotten a
1651 spurious result because of insufficient precision or rounding anomalies.
1653 A. The decimal module makes it easy to test results.  A best practice is to
1654 re-run calculations using greater precision and with various rounding modes.
1655 Widely differing results indicate insufficient precision, rounding mode issues,
1656 ill-conditioned inputs, or a numerically unstable algorithm.
1658 Q. I noticed that context precision is applied to the results of operations but
1659 not to the inputs.  Is there anything to watch out for when mixing values of
1660 different precisions?
1662 A. Yes.  The principle is that all values are considered to be exact and so is
1663 the arithmetic on those values.  Only the results are rounded.  The advantage
1664 for inputs is that "what you type is what you get".  A disadvantage is that the
1665 results can look odd if you forget that the inputs haven't been rounded::
1667    >>> getcontext().prec = 3
1668    >>> Decimal('3.104') + D('2.104')
1669    Decimal('5.21')
1670    >>> Decimal('3.104') + D('0.000') + D('2.104')
1671    Decimal('5.20')
1673 The solution is either to increase precision or to force rounding of inputs
1674 using the unary plus operation::
1676    >>> getcontext().prec = 3
1677    >>> +Decimal('1.23456789')      # unary plus triggers rounding
1678    Decimal('1.23')
1680 Alternatively, inputs can be rounded upon creation using the
1681 :meth:`Context.create_decimal` method::
1683    >>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
1684    Decimal('1.2345')